duanshan3065 2018-07-21 12:50
浏览 315
已采纳

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

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.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
", 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.

So my question here is, does it possible to set that http.ResponseWriter Content-Type header globally for all API functions that I have?

  • 写回答

1条回答 默认 最新

  • duangu9173 2018-07-21 12:59
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作