英文:
Golang net/http package Post call returns base64
问题
一些原因导致下面的调用返回了Base64字符串而不是XML输出。我需要解码它以查看XML。
// POST
func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
Api := new(Api)
Api.url = "http://api.com"
usr := new(User)
err := request.ReadEntity(usr)
if err != nil {
response.AddHeader("Content-Type", "application/json")
response.WriteErrorString(http.StatusInternalServerError, err.Error())
return
}
buf := []byte("<api version=\"6.0\"><request>test</request></api>")
r, err := http.Post(Api.url, "text/plain", bytes.NewBuffer(buf))
if err != nil {
response.AddHeader("Content-Type", "plain/text")
response.WriteErrorString(http.StatusInternalServerError, err.Error())
return
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
response.WriteHeader(http.StatusCreated)
response.WriteEntity(body)
}
有没有办法防止这种情况发生,并获得正确的XML输出?
英文:
Somehow below call returns base64 string instead of xml output. I need to decode this to see xml.
// POST
func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
Api := new(Api)
Api.url = "http://api.com"
usr := new(User)
err := request.ReadEntity(usr)
if err != nil {
response.AddHeader("Content-Type", "application/json")
response.WriteErrorString(http.StatusInternalServerError, err.Error())
return
}
buf := []byte("<api version=\"6.0\"><request>test</request></api>")
r, err := http.Post(Api.url, "text/plain", bytes.NewBuffer(buf))
if err != nil {
response.AddHeader("Content-Type", "plain/text")
response.WriteErrorString(http.StatusInternalServerError, err.Error())
return
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
response.WriteHeader(http.StatusCreated)
response.WriteEntity(body)
}
Is there a way to prevent this from happening and have correct xml output?
答案1
得分: 3
代码使用Go-Restful的WriteEntity方法将包含XML的[]byte写入响应体中。WriteEntity方法使用标准编码包将值编组为XML或JSON。这些包将[]byte值编组为base64字符串。
将上面的最后一行更改为
response.Write(body)
将以不进行JSON或XML编码的方式将远程服务器的响应写入客户端。
英文:
The code uses the Go-Restful WriteEntity method to write a []byte containing XML to the response body. The WriteEntity method marshals the value to XML or JSON using the standard encoding packages. These packages marshal []byte values as base64 strings.
Changing the last line above to
response.Write(body)
will write the remote server's response to the client without JSON or XML encoding.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论