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\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)
}

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

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

推荐答案

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

Json相关问答推荐

Jolt Transformation—如果子对象为空,则将父对象更新为空

如何获取brew list作为JSON输出

合并二维数组的Jolt表达式

Terraform迭代JSON文件以获取键值对

如何从一个700MB的json文件中列出PowerShell中的所有密钥?

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

条件性构建/修改嵌套对象数组

JOLT 转换仅过滤一个字段

是否可以在有条件的情况下将 json 对象转换为 JOLT 中的数组?

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

在 Flutter 中将对象转换为可编码对象失败

Servicestack 返回数组而不是带有数组的对象

如何使用 LINQ 在 C# 中重构对象?

将 JSON 对象推送到 localStorage 中的数组

使用 API 搜索维基百科

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

在 HTML 数据属性上添加 JSON 是不是很糟糕?

POST:在 url 本身中发送 post 请求

PHP json_encode json_decode UTF-8

添加json文件注释