I am trying to understand how to implement http.Handler, correctly. I wrote the barebone package code. Here is my package code
package app
import (
"fmt"
"net/http"
)
//Handler is the handler function
type Handler struct {
}
func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
fmt.Println("Running ServeHTTP")
rw.Write(([]byte)("Hello"))
return
}
//NewHandler is
func NewHandler() *Handler {
return &Handler{}
}
//Start will start the server
func (h *Handler) Start() {
fmt.Println("Running Start")
http.ListenAndServe("8080", h)
}
I made a directory in the abovementioned package named it "examples". I made a file main.go
and wrote this in main function(After importing the Package).
func main() {
handler := app.NewHandler()
handler.Start()
}
But, when I run it with go run *.go
, The Program abrupts almost instantly after writing Running Start
on console. Shouldn't it listen continuouly. What am I doing wrong?
The http.ListenAndServe()
func returns error. You could just check that by logging:
fmt.Println(http.ListenAndServe("8000", h))
and you will see that in your case its returning an error causing the function to return.
All you need to do is to pass address as :8000