[zeromicro/go-zero]开启验签功能解出明文后拿不到请求参数

2024-02-18 811 views
9

1.验证逻辑已经通过 2.密文也成功解密 3.拿到解密后明文后,框架是通过ioutil.NopCloser(&buf)重新赋值给request.Body对象,具体代码入下:https://github.com/tal-tech/go-zero/blob/master/rest/handler/cryptionhandler.go#L72

4.经过测试,框架request.Parse方法拿不到第3条中Body的值。 5.测试代码如下:

func TestParse(t *testing.T) {
      var v struct {
          Name    string  `json:"name"`
          Age     int     `json:"age"`
          Percent float64 `json:"percent,optional"`
      }

      r, err := http.NewRequest(http.MethodGet, "http://hello.com/", nil)
      var buf bytes.Buffer
      json := `{"name":"hello","age":18}`
      _, _ = buf.Write([]byte(json))
      r.Body = ioutil.NopCloser(&buf)
      r.ContentLength = int64(len(json))
      assert.Nil(t, err)
      assert.Nil(t, Parse(r, &v))
      assert.Equal(t, "hello", v.Name)
      assert.Equal(t, 18, v.Age)
  }

测试结果:


    requests_test.go:28: 
            Error Trace:    requests_test.go:28
            Error:          Expected nil, but got: &errors.errorString{s:"field name is not set"}
            Test:           TestParse
    requests_test.go:29: 
            Error Trace:    requests_test.go:29
            Error:          Not equal: 
                            expected: "hello"
                            actual  : ""

                            Diff:
                            --- Expected
                            +++ Actual
                            @@ -1 +1 @@
                            -hello
                            +
            Test:           TestParse
    requests_test.go:30: 
            Error Trace:    requests_test.go:30
            Error:          Not equal: 
                            expected: 18
                            actual  : 0
            Test:           TestParse

回答

3
func TestParse(t *testing.T) {
    var v struct {
        Name    string  `json:"name"`
        Age     int     `json:"age"`
        Percent float64 `json:"percent,optional"`
    }

    r, err := http.NewRequest(http.MethodGet, "http://hello.com/", nil)
    var buf bytes.Buffer
    json := `{"name":"hello","age":18}`
    _, _ = buf.Write([]byte(json))
    r.Body = ioutil.NopCloser(&buf)
    r.Header.Set("Content-Type", "application/json")
    r.ContentLength = int64(buf.Len())
    assert.Nil(t, err)
    assert.Nil(t, Parse(r, &v))
    assert.Equal(t, "hello", v.Name)
    assert.Equal(t, 18, v.Age)
}
8

@knight0zh 搞定了吗?