How to get the JSON from the Body of a Request on Go

前端 未结 2 1977
星月不相逢
星月不相逢 2020-12-30 14:57

I\'m a newbie with Go, but so far I\'m liking it very much.

I have a problem I can\'t figure out. I\'m migrating an API from Node to Go and there is this log where I

相关标签:
2条回答
  • 2020-12-30 15:26

    TIL that http.Response.Body is a buffer, which means that once it has been read, it cannot be read again.

    It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.

    However, knowing this, there is a workaround, you need to "catch" the body and restore it:

    // Read the Body content
    var bodyBytes []byte
    if context.Request().Body != nil {
        bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
    }
    
    // Restore the io.ReadCloser to its original state
    context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
    
    // Continue to use the Body, like Binding it to a struct:
    order := new(models.GeaOrder)
    error := context.Bind(order)
    

    Now, you can use context.Request().Body somewhere else.

    Sources:

    http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader

    https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361

    0 讨论(0)
  • 2020-12-30 15:42

    I believe you can do this:

    m := make(map[string]interface{});
    if err := context.Bind(&m); err != nil {
        return result, err
    }
    fmt.Println(m)
    
    0 讨论(0)
提交回复
热议问题