我试图让Error
和Success
结构消失,如果他们中的任何一个为空Golang - 从JSON响应隐藏空结构
package main
import (
"encoding/json"
"net/http"
)
type appReturn struct {
Suc *Success `json:"success,omitempty"`
Err *Error `json:"error,omitempty"`
}
type Error struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
type Success struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
j := appReturn{&Success{}, &Error{}}
js, _ := json.Marshal(&j)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
输出:
{
success: { },
error: { }
}
我怎么能隐藏来自JSON输出的Error
或Success
结构? 我认为发送指针作为参数会做的伎俩。