How to set http.ResponseWriter Content-Type header globally for all API endpoints?

You can define middleware for mux router, here is an example:

func main() {
    port := ":3000"
    var router = mux.NewRouter()
    router.Use(commonMiddleware)

    router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")
    router.HandleFunc("/n/{num}", handleNumber).Methods("GET")
    // rest of code goes here
}

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

Read more in the documentation

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)