简体   繁体   English

如何为所有API端点全局设置http.ResponseWriter Content-Type标头?

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

I am new to Go and I'm building a simple API with it now: 我是Go的新手,我现在用它构建一个简单的API:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/handlers"
    "log"
    "net/http"
)

func main() {
    port := ":3000"
    var router = mux.NewRouter()
    router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")
    router.HandleFunc("/n/{num}", handleNumber).Methods("GET")

    headersOk := handlers.AllowedHeaders([]string{"Authorization"})
    originsOk := handlers.AllowedOrigins([]string{"*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})

    fmt.Printf("Server is running at http://localhost%s\n", port)
    log.Fatal(http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}

func handleMessage(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    message := vars["msg"]
    response := map[string]string{"message": message}
    w.Header().Set("Content-Type", "application/json") // this
    json.NewEncoder(w).Encode(response)
}

func handleNumber(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    number := vars["num"]
    response := map[string]string{"number": number}
    w.Header().Set("Content-Type", "application/json") // and this
    json.NewEncoder(w).Encode(response)
}

I feel like it's not clean to keep repeating w.Header().Set("Content-Type", "application/json") line in every API function that I have. 我觉得继续重复w.Header().Set("Content-Type", "application/json")并不干净w.Header().Set("Content-Type", "application/json")在我拥有的每个API函数中w.Header().Set("Content-Type", "application/json")行。

So my question here is, does it possible to set that http.ResponseWriter Content-Type header globally for all API functions that I have? 所以我的问题是,是否可以为我拥有的所有API函数全局设置http.ResponseWriter Content-Type标头?

You can define middleware for mux router, here is an example: 您可以为mux路由器定义middleware ,这是一个示例:

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 阅读文档中的更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM