Gorilla mux json header for all routes golang

Issue

Is there a way to set json header to all routes?

func Ping(rw http.ResponseWriter, r *http.Request) {
  rw.Header().Set("Content-Type", "application/json")

  json.NewEncoder(rw).Encode(map[string]string{"Status": "OK"})
}
func Lol(rw http.ResponseWriter, r *http.Request) {
  rw.Header().Set("Content-Type", "application/json")

  json.NewEncoder(rw).Encode(map[string]string{"Status": "OK"})
}

not to duplicate this

json.NewEncoder(rw).Encode(map[string]string{"Status": "OK"})

Solution

You can use middleware to add Content-Type: application/json header to each handler

func contentTypeApplicationJsonMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        next.ServeHTTP(w, r)
    })
}

Then register the middleware to gorilla/mux as below

r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(contentTypeApplicationJsonMiddleware)

Answered By – Chandan

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.