duanquan1243 2016-12-12 20:33
浏览 93
已采纳

Golang杜松子酒gonic内容类型未使用c.JSON设置为application / json

According to the official documentation, c.JSON of gin-gonic should set the response header to application/json, but when I call my API from Postman, the response header is set to text/plain; charset=utf-8

I don't understand what I am missing, any idea ?

Doc :

func JSON

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

Here is a sample of my code :

func postLogin(c *gin.Context) {
    var credentials DTO.Credentials
    if err := c.BindJSON(&credentials); err == nil {
        c.JSON(buildResponse(services.CheckUserCredentials(credentials)))
    } else {
        var apiErrors = DTO.ApiErrors{}
        for _, v := range err.(validator.ValidationErrors) {
            apiErrors.Errors = append(apiErrors.Errors, DTO.ApiError{Field: v.Field, Message: v.Field + " is " + v.Tag})
        }
        c.JSON(http.StatusBadRequest, apiErrors)
    }
}

EDIT

After investigation, log.Println(c.Writer.Header().Get("Content-Type")) doesn't print any thing, showing content-type is empty as it should be.

func writeContentType(w http.ResponseWriter, value []string) {
    header := w.Header()
    log.Println(header.Get("Content-Type")) // <=========== Nothing happen
    if val := header["Content-Type"]; len(val) == 0 {
        header["Content-Type"] = value
    }
}

I really don't want to have to add c.Writer.Header().Set("Content-Type", "application/json") to every route in my architecture...

EDIT 2

It seems like binding:"required" break the Content-Type Header

type Credentials struct {
    Email         string        `json:"email" binding:"required"`
    Password      string        `json:"password" binding:"required"`
}
  • 写回答

1条回答 默认 最新

  • dsm0688 2016-12-12 20:59
    关注

    After looking at the source, it looks like it won't write the Content-Type header if it is already set.

    c.JSON calls this function which calls the following code:

    func writeContentType(w http.ResponseWriter, value []string) {
        header := w.Header()
        if val := header["Content-Type"]; len(val) == 0 {
            header["Content-Type"] = value
        }
    }
    

    Therefore your Content-Type must be set somewhere else.

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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制