英文:
How can I return an encoded string in an http response body?
问题
将编码字符串添加到HTTP响应中时,似乎会将一些字符替换为!F(MISSING)。如何防止这种情况发生?
输出:
{"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))
}
英文:
Adding an encoded string to an http resonse seems to replace some characters with !F(MISSING). How that that be prevented?
Output:
{"encodedText":"M6c8RqL61nMFy%!F(MISSING)hQmciSYrh9ZXgVFVjO"}
Code:
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))
}
答案1
得分: 1
这是要翻译的内容:
似乎它正常地进行了转义,你能贴一些代码吗?
package main
import (
"fmt"
"net/url"
)
func main() {
escape := url.QueryEscape("M6c8RqL61nMFy/hQmciSYrh9ZXgVFVjO")
fmt.Println(escape)
}
英文:
It appears to be escaping it normally, can you paste some code?
http://play.golang.org/p/rUEGn-KlTX
package main
import (
"fmt"
"net/url"
)
func main() {
escape := url.QueryEscape("M6c8RqL61nMFy/hQmciSYrh9ZXgVFVjO")
fmt.Println(escape)
}
答案2
得分: 0
你正在这一行中使用转义值"M6c8RqL61nMFy%2FhQmciSYrh9ZXgVFVjO"作为格式化字符串:
fmt.Fprintf(w, string(response))
Fprintf尝试为动词"%2F"格式化一个参数。由于没有参数,所以Fprintf会打印"%!F(MISSING)"作为动词。
修复的方法是不要将输出用作格式化字符串。因为在写入响应时不需要任何格式化,所以将最后一行改为:
w.Write(response)
英文:
You are using the escaped value "M6c8RqL61nMFy%2FhQmciSYrh9ZXgVFVjO " as a format string on this line:
fmt.Fprintf(w, string(response))
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论