douguadao3883 2015-05-18 18:04
浏览 46

Go-中间件阻止每个请求的MIME类型

I modiefied the middleware of this tutorial to check for all PUT and POST request the JSON MIME type.

But the middleware seems to respond everytime with "Mediatype Not Supported". I tried the curl command below where I set explicitly the right MIME type. I print which each request the client's Content-Type header field which is allways "text/plain; charset=utf-8".

The Middleware:

func EnforceJSON(h httprouter.Handle) httprouter.Handle {
    return func(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        // Check the existence of a request body
        if req.ContentLength == 0 {
            http.Error(rw, http.StatusText(400), http.StatusBadRequest)
            return
        }

        // Check the MIME type
        buf := new(bytes.Buffer)
        buf.ReadFrom(req.Body)
        // Prints "text/plain; charset=utf-8"
        fmt.Println(http.DetectContentType(buf.Bytes()))
        if http.DetectContentType(buf.Bytes()) != "application/json; charset=utf-8" {
            http.Error(rw, http.StatusText(415), http.StatusUnsupportedMediaType)
            return
        }

        h(rw, req, ps)
    }
}  
...
router.POST("/api/v1/users", EnforceJSON(CreateUser))

My curl command:

curl -H "Content-Type: application/json; charset=utf-8" \
-X POST \
-d '{"JSON": "Will be checked after the middleware accepted the MIME type."}' \
http://localhost:8080/api/v1/users

Alternativly I tried Postman but the result was the same.

  • 写回答

1条回答 默认 最新

  • donglu1472 2019-01-09 11:10
    关注

    Looking at the implementation of DetectContentType function they follow the rules described on "MIME Sniffing" guide (https://mimesniff.spec.whatwg.org/).

    To determine the MIME Type by the content this specific function use the item "7. Determining the computed MIME type of a resource". That item doesn't have a determination for 'application/json' type and following these rules will result in a 'text/plain' MIME type.

    This is visible on the function match on the DetectContentType implementation (https://golang.org/src/net/http/sniff.go) line 252.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答