DEV Community

loading...

Discussion on: Build Your First Rest API with GO

Collapse
ajeyprasand profile image
ajeyprasand

bro thanks for the article however why did u did not add any code in the stuct called server initially ??

Collapse
moficodes profile image
Mofizur Rahman Author
type server struct{}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
    w.Write([]byte(`{"message": "hello world"}`))
}

You are talking about this part I believe.

For http.Handle it just needs some type that implements the handler interface.

For example, this below is valid code.

type hotdog int

func (s *hotdog) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
    w.Write([]byte(`{"message": "hello world"}`))
}

func main() {
    var s hotdog
    http.Handle("/", &s)
    log.Fatal(http.ListenAndServe(":8080", nil))
}