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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看