如何在http响应正文中返回编码的字符串? [英] How can I return an encoded string in an http response body?
问题描述
在http共振中添加编码字符串似乎用!F(MISSING)替换了某些字符。
Adding an encoded string to an http resonse seems to replace some characters with !F(MISSING). How that that be prevented?
输出:
{ encodedText: M6c8RqL61nMFy%!F(MISSING )hQmciSYrh9ZXgVFVjO}
{"encodedText":"M6c8RqL61nMFy%!F(MISSING)hQmciSYrh9ZXgVFVjO"}
代码:
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type EncodeResult struct {
EncodedText string `json:"encodedText"`
}
func main() {
http.HandleFunc("/encodedString", encodedString)
_ = http.ListenAndServe(":8080", nil)
}
func encodedString(w http.ResponseWriter, r *http.Request) {
inputString := "M6c8RqL61nMFy/hQmciSYrh9ZXgVFVjO"
er := EncodeResult{url.QueryEscape(inputString)}
response, _ := json.Marshal(er)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(response))
}
推荐答案
您正在使用转义的值 M6c8RqL61nMFy%2 FhQmciSYrh9ZXgVFVjO作为此行上的格式字符串:
You are using the escaped value "M6c8RqL61nMFy%2FhQmciSYrh9ZXgVFVjO " as a format string on this line:
fmt.Fprintf(w, string(response))
Fprintf尝试格式化动词%2F的自变量。没有参数,因此Fprintf为动词打印%!F(MISSING)。
Fprintf attempts to format an argument for the verb "%2F". There is no argument, so Fprintf prints "%!F(MISSING)" for the verb.
解决方法是不要将输出用作格式字符串。因为写入响应时不需要任何格式,所以将最后一行更改为:
The fix is to not use the output as a format string. Because you don't need any formatting when writing to the response, change the last line to:
w.Write(response)
这篇关于如何在http响应正文中返回编码的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!