如何从请求中读取,然后使用该结果执行POST请求,然后处理其结果

如何从请求中读取,然后使用该结果执行POST请求,然后处理其结果

问题描述:

I'm trying to read from request then use that result to do POST request to another endpoint then process its results then return its results in JSON.

I have below code so far:

// POST 
func (u *UserResource) authenticate(request *restful.Request, response *restful.Response) {
    Api := Api{url: "http://api.com/api"}
    usr := new(User)
    err := request.ReadEntity(&usr)
    if err != nil {
        response.WriteErrorString(http.StatusInternalServerError, err.Error())
        return
    }

    api_resp, err := http.Post(Api.url, "text/plain", bytes.NewBuffer(usr))
    if err != nil {
        response.WriteErrorString(http.StatusInternalServerError, err.Error())
        return
    }
    defer api_resp.Body.Close()
    body, err := ioutil.ReadAll(api_resp.Body)
    response.WriteHeader(http.StatusCreated)
    err = xml.Unmarshal(body, usr)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
//  result, err := json.Marshal(usr)
//  response.Write(result)
    response.WriteEntity(&usr)
    fmt.Printf("Name: %q
", usr.UserName)
}

I'm using Go Restful package for Writes and Reads.

I'm getting this error when I compile the file:

src\login.go:59: cannot use usr (type *User) as type []byte in argument to bytes.NewBuffer

What would be the best way to solve this issue so I can do a POST with payload correctly?

You need to marshal your data structure to slice of bytes. Something like this:

usrXmlBytes, err := xml.Marshal(usr)
if err != nil {
    response.WriteErrorString(http.StatusInternalServerError, err.Error())
    return
}
api_resp, err := http.Post(Api.url, "text/plain", bytes.NewReader(usrXmlBytes))

http.Post takes an io.Reader as the third argument. You could implement io.Reader on your User type or more simply serialize your data and use the bytes pkg to to implement io.Reader

b, err := json.Marshal(usr)
if err != nil {
    response.WriteErrorString(http.StatusInternalServerError, err.Error())
    return
}
api_resp, err := http.Post(Api.url, "text/plain", bytes.NewReader(b))