http.Error调用时可以返回json吗?
myObj := MyObj{
MyVar: myVar}
data, err := json.Marshal(myObj)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
w.Header().Set("Content-Type", "application/json")
http.Error(w, "some error happened", http.StatusInternalServerError)
Run Code Online (Sandbox Code Playgroud)
我看到它返回200没有json但是json被嵌入text
cra*_*gmj 11
我发现阅读 Go 源代码真的很容易。如果您单击文档中的函数,您将被带到该Error函数的源代码:https : //golang.org/src/net/http/server.go?s=61907 : 61959#L2006
// Error replies to the request with the specified error message and HTTP code.
// It does not otherwise end the request; the caller should ensure no further
// writes are done to w.
// The error message should be plain text.
func Error(w ResponseWriter, error string, code int) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
fmt.Fprintln(w, error)
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您想返回 JSON,编写自己的 Error 函数就很容易了。
func JSONError(w http.ResponseWriter, err interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
json.NewEncoder(w).Encode(err)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4905 次 |
| 最近记录: |