Home > Software engineering >  Gorilla mux json header for all routes golang
Gorilla mux json header for all routes golang

Time:05-06

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"})

CodePudding user response:

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)

CodePudding user response:

Is there a way to set json header to all routes [handled by Gorilla mux]?

No. You have to write your own function for this.

  • Related