DEV Community

Discussion on: Build Your First Rest API with GO

Collapse
 
moficodes profile image
Mofi Rahman
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))
}