D_M
D_M

Reputation: 55

Gorilla mux json header for all routes golang

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

Upvotes: 1

Views: 2239

Answers (1)

Chandan
Chandan

Reputation: 11807

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)

Upvotes: 4

Related Questions