Read multiple time a Reader

痴心易碎 提交于 2020-12-29 07:53:27

问题


I have two http handlers that use the same http.ResponseWriter and *http.Request and read the request body like this:

func Method1 (w http.ResponseWriter, r *http.Request){
    var postData database.User
    if err := json.NewDecoder(r.Body).Decode(&postData); err != nil {
      //return error
    }
}

func Method2 (w http.ResponseWriter, r *http.Request){
    var postData database.User
    //this read gives (of course) EOF error
    if err := json.NewDecoder(r.Body).Decode(&postData); err != nil {
      //return error
    }
}

Because of I need to keep these 2 methods separated, and both of them need to read the request Body, which is the best way (if it's possible) to Seek the request body (which is a ReadCloser, not a Seeker?).


回答1:


Actually, thanks to miku, I've found out that the best solution is using a TeeReader, changing Method1 in this way

func Method1 (w http.ResponseWriter, r *http.Request){
    b := bytes.NewBuffer(make([]byte, 0))
    reader := io.TeeReader(r.Body, b)

    var postData MyStruct
    if err := json.NewDecoder(reader).Decode(&postData); err != nil {
        //return an error
    }

    r.Body = ioutil.NopCloser(b)
}


来源:https://stackoverflow.com/questions/31884093/read-multiple-time-a-reader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!