duanjian5059 2017-08-11 09:01
浏览 27

从中间件发送帖子请求

I want to make middleware func to check token's validity, but at the end function I cannot get post value of it's request.

Here I put "brief" (code just to show the main idea)

func main() {
  http.Handle("/100000/000001", Verify(http.HandlerFunc(Insert)))
}

func Verify(next http.Handler) http.Handler
{
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      var reqBody RequestBody
      decoder := json.NewDecoder(r.Body)
      err := decoder.Decode(&reqBody)
      Util.CheckErr(err)
      var token = RequestHeader{Token: r.Header.Get("_Token")}

      if token == dbToken {
        next.ServeHTTP(w, r)
      } else {
        Util.PutResponseMessage(w, "003", "Access danied")
      }

   })
}

func Insert(res http.ResponseWriter, req *http.Request) {
  var requestBody InsertRequestBody
    decoder := json.NewDecoder(req.Body)
    err := decoder.Decode(&requestBody)
    if err != nil {
        panic(err)
    }

    defer req.Body.Close()

    log.Println(requestBody.Username)
}

I get error like this :

http: panic serving [::1]:51269: EOF
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc0420348c0)
    C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x6884e0, 0xc042008110)

But, If I directly return next.ServeHttp(r, w)

like this :

func Verify(next http.Handler) http.Handler
{
      next.ServeHTTP(w, r)
}

Then decoding process in Insert func working perfectly.

Why is it? Any answer will highly appreciated. Thankyou

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
    • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
    • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
    • ¥15 帮我写一个c++工程
    • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法