小编soa*_*mya的帖子

POST请求有效内容的内容类型

我在POST请求中发送了JSON正文,但是http.DetectContentType将其标识为文本/纯文本类型。

我想灵活地根据其内容类型来处理请求有效负载-如果是XML {}如果是JSON {}否则是{否处理}

为了实现此条件处理,我使用http.DetectContentType返回请求的内容类型,但在每种情况下都将返回文本/纯文本。

func Test(w http.ResponseWriter, r *http.Request) *ErrorObject {

        reqBuffer := make([]byte, 512)
        _, err := r.Body.Read(reqBuffer)
        if err != nil {

    return ErrorObject{}.New(1, err, nil)
}

contentType := GetContentType(reqBuffer)
fmt.Printf(contentType)

    if contentType == "application/xml" || contentType == "text/xml" {
    w.Header().Set("Content-Type", "application/xml; charset=UTF-8") ...}
    if contentType == "application/json" || contentType == "text/json" {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8") ... } 
    else return Invalid Request Type error
} 

   func GetContentType(buffer []byte) string {

       fmt.Println(string(buffer))
       contentType := http.DetectContentType(buffer)
       fmt.Printf(contentType)
       return contentType …
Run Code Online (Sandbox Code Playgroud)

xml rest json http-post go

0
推荐指数
1
解决办法
283
查看次数

标签 统计

go ×1

http-post ×1

json ×1

rest ×1

xml ×1