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

祖尔米·扎努丁(Zulhilmi Zainudin):

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

我觉得w.Header().Set("Content-Type", "application/json")在我拥有的每个API函数中都重复是不干净的

所以我的问题是,是否可以为我拥有的所有API函数全局设置http.ResponseWriter Content-Type标头?

绿色:

您可以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)
    })
}

文档中阅读更多内容

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

HTTP“ Content-Type”标头的所有可能值是什么?

如何设置HttpClient请求的Content-Type标头?

未使用Angular $ http设置Content-Type标头

如何访问NSHTTPURLResponse的“ Content-Type”标头?

无法设置Content-Type标头

如何设置JMS消息的Content-Type标头

Content-Type标头未在Tornado中设置

如何告诉Angular 2自动停止设置Content-Type标头?

我应该为哪些Content-Type设置与安全性相关的HTTP响应标头?

如何将content-type标头设置为空?

何时获取API,我应该显式设置“ Content-Type”标头?

AngularJS $ http删除请求Content-Type标头

如何在GmailApp.sendmail中设置Content-type和MIME-Version标头?

如何指定喷雾Content-Type响应标头?

REST WEB API:如何使Content-Type标头为可选?

如何设置RestRequest的Content-Type标头?

如何使用代理接口在RestEasy Client框架中设置“ Content-type”标头?

喷不设置FormData的Content-Type标头

http accept和content-type标头混淆

节点,尽管设置了application / javascript,express app仍返回text / javascript响应标头(Content-Type)

将content-type标头设置为json以获取request.post

为什么只有在设置了 Content-Type HTTP 标头时,对我的 Web API 的请求才会成功?

设置 Content-Type 标头

在 HttpWebRequest 中设置“Content-Type”标头的最佳方法?

无法将 Content-Type 标头添加到 SSE 端点

如何使用 Content-Type 标头创建响应?

Paw - 如何禁用 Content-Type 标头?

Apache Server 未为一个特定路径设置 Content-Type 标头

在 Spring Boot 中动态设置 Content-Type 标头