Golang的net/http包中的Post调用返回base64编码。

huangapple go评论73阅读模式
英文:

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 = &quot;http://api.com&quot;
	usr := new(User)
	err := request.ReadEntity(usr)
	if err != nil {
		response.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
		return
	}

	buf := []byte(&quot;&lt;api version=\&quot;6.0\&quot;&gt;&lt;request&gt;test&lt;/request&gt;&lt;/api&gt;&quot;)

	r, err := http.Post(Api.url, &quot;text/plain&quot;, bytes.NewBuffer(buf))
	if err != nil {
		response.AddHeader(&quot;Content-Type&quot;, &quot;plain/text&quot;)
		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.

huangapple
  • 本文由 发表于 2014年9月16日 20:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/25869217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定