0

The if branch in the snippetCreate func below doesn't reach when I make requests other than POST:

func snippetCreate(w http.ResponseWriter, r *http.Request) {
    // anything under this if statement doesnt work, I tried even write logs and fmt prints
    // tested with different requests other than POST
    if r.Method != "POST" {
        w.Header().Set("Allow", "POST")
        http.Error(w, "Method Not Allowed", 405)
        return
    }
    // it works
    w.Header().Set("Allow", "POST")

    w.Write([]byte("create a snippet"))

}
    
func main() {

    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Get("/", home)
    r.Get("/snippet/view", snippetView)
    r.Post("/snippet/create", snippetCreate)

    log.Print("Starting server on port :8080")
    err := http.ListenAndServe(":8080", r)
    if err != nil {
        log.Fatal(err)

    }
}
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23

1 Answers1

1

r.Post("/snippet/create", snippetCreate)

Note the Post here. Only POST requests will be routed to the handler snippetCreate.

So in the handler snippetCreate, r.Method will always be POST. See the doc for (*Mux).Post:

Post adds the route pattern that matches a POST http method to execute the handlerFn.

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23