How to call handler to main in different go file

main.go
package main

import (
“fmt”
“net/http”
)

func ccc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Hello, you’ve requested: %s\n”, r.URL.Path)
}

func main() {
http.HandleFunc("/",ccc)

http.ListenAndServe(":80", nil)

}


I want bellow code in folder/xx.go and remove from main.go

func ccc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Hello, you’ve requested: %s\n”, r.URL.Path)
}

Thanks experts

Shall xx.go be part of the same package as main.go is? Is there any reason why you want to put it into a subfolder?

Thanks for your reply… xx.go will be the seen all the functions and the main is the router. Is there any chance to do like that? second point is to organize well the go files

All the files in a package live in a single directory. You can not use a structure like this:

+ main.go
+ folder
   + xx.go

Organize the files like this:

+ main.go
+ xx.go

Make all files part of the main package:

package main

See https://talks.golang.org/2014/organizeio.slide#5

Thanks, Im doing these way in same directory?

package main

import (
“fmt”
“net/http”
“xy”
)

func main() {
http.HandleFunc("/",xy.ccc)

http.ListenAndServe(":80", nil)

}


package xy

import (
“fmt”
“net/http”
)
func ccc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Test”)
}

Showing cannot load the package

If you want to import a function from package xy and use it in your main application ( package main), the function must be exported. To export a function, name it with an upppercase first letter:


package xy

// ...

func Ccc((w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, “Test”)
}

Then you can use the imported function in your main package:

package main

// ...

func main() {
  http.HandleFunc("/",xy.Ccc)

  http.ListenAndServe(":80", nil)
}

Take a look at the tour: https://tour.golang.org/basics/3

Also see https://www.ardanlabs.com/blog/2014/03/exportedunexported-identifiers-in-go.html

1 Like

sorry dude, i can’t really get the way it used to be. Sorry i’m newbie in go lang.

If you are a newbie you should take the Go tour: https://tour.golang.org/welcome/1

After the tour read these:

thank you. have you tried the same way i’m trying to figure out. Did you got successful compilation?

dude thanks alot… i got it… thank you thank you…

i put also in different directory… but i follow your advice that need comment and Uppercase of the starting of the function

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.