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

前端 未结 1 1765
陌清茗
陌清茗 2021-02-04 00:53

I am new to Go and I\'m building a simple API with it now:

package main

import (
    \"encoding/json\"
    \"fmt\"
    \"github.com/gorilla/mux\"
    \"github.c         


        
1条回答
  •  被撕碎了的回忆
    2021-02-04 01:16

    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

    0 讨论(0)
提交回复
热议问题