I'm writing a kind of framework and I would like to make the initialisation of the http server part of this framework. So basically I have a package internal
as below which is imported by the framework middleware:
package internal
import(
"net/http"
"log"
)
func main() {
checkHealth(http.DefaultServeMux)
if err := http.ListenAndServe(":8080", http.HandlerFunc(handleHTTP)); err != nil {
log.Fatalf("http.ListenAndServe: %v", err)
}
}
In the app code I'm looking to define the handlers in an init function. e.g.
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, world!")
}
However if I run go build
in the app code directory/package it errors out that the main function is not defined: runtime.main_main: main.main: not defined runtime.main_main: undefined: main.main
So my question is how should I build / compile the program so and why using the standard go build
command it doesn't find the main function defined in the internal package.
The main
function must be in the main
package: Program Execution
Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.
If you want a package to initialize some state at start up, or have side-effects by simply importing it, you use an init function
. The init however must return, so you can't block with it http.ListenAndServe
.