Gorilla mux json header 适用于所有路线 golang

Gorilla mux json header for all routes golang

有没有办法将json header设置为所有路由?

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

不要重复这个

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

您可以使用 middlewareContent-Type: application/json header 添加到每个处理程序

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

然后将middleware注册到gorilla/mux如下

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