-2

I was trying to build basic web API using gorilla mux in Go. Here is my code. Please help me understand how some interfaces are working here.

func main() {
    r := mux.NewRouter()

    r.Handle("/", http.FileServer(http.Dir("./views/")))
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))

    r.Handle("/status", myHandler).Methods("GET")

    http.ListenAndServe(":8080", r)

}

func myHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)

} ```


error :- `cannot use myHandler (value of type func(w http.ResponseWriter, r *http.Request)) as http.Handler value in argument to r.Handle: missing method ServeHTTP `
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jagdish
  • 9
  • 1
  • 1
  • You don't seem to use it in a correct way: the examples clearly state that you need to use "r.HandleFunc" to set handlers and finally use "http.Handle(path, r)" – mangusta Aug 11 '20 at 16:01
  • 1
    You want to use HandleFunc("/status... instead of Handle("status.... – SamuelTJackson Aug 11 '20 at 16:01
  • yes sir i found my mistake i was following wrong tutotial @ https://auth0.com/blog/authentication-in-golang/#Building-an-API-in-Go. thanks for your quick repsonse. – jagdish Aug 11 '20 at 16:04

1 Answers1

1

As the docs for mux.Router.Handle show, it takes a http.Handler. This is an interface with a single method: ServeHTTP(ResponseWriter, *Request).

This is useful if you want to pass an object as a handler.

To register the function myHandler, use mux.Router.HandleFunc instead:

r.HandleFunc("/status", myHandler)

This is also shown in the basic examples of the mux package.

Marc
  • 19,394
  • 6
  • 47
  • 51
  • yess exactly, i literally asked this question and later saw it on some other question. actually i was following this tutorial https://auth0.com/blog/authentication-in-golang/#Building-an-API-in-Go that is why it went wrong. Thanks alot for such a quick response. – jagdish Aug 11 '20 at 16:03