douji1877 2014-09-17 13:44
浏览 42
已采纳

如何从请求中读取,然后使用该结果执行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?

  • 写回答

2条回答 默认 最新

  • dongyou2714 2014-09-17 15:00
    关注

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题