MCPcopy Create free account
hub / github.com/DoNewsCode/core / encode

Function encode

srvhttp/encode.go:63–96  ·  view source on GitHub ↗
(w http.ResponseWriter, any interface{}, code int)

Source from the content-addressed store, hash-verified

61}
62
63func encode(w http.ResponseWriter, any interface{}, code int) {
64 const contentType = "application/json; charset=utf-8"
65 w.Header().Set("Content-Type", contentType)
66
67 if headerer, ok := any.(Headerer); ok {
68 for k := range headerer.Headers() {
69 w.Header().Set(k, headerer.Headers().Get(k))
70 }
71 }
72 if sc, ok := any.(StatusCoder); ok {
73 code = sc.StatusCode()
74 }
75 w.WriteHeader(code)
76
77 switch x := any.(type) {
78 case json.Marshaler:
79 encoder := json.NewEncoder(w)
80 _ = encoder.Encode(x)
81 case proto.Message:
82 bytes, _ := protojson.MarshalOptions{
83 EmitUnpopulated: true,
84 UseProtoNames: true,
85 }.Marshal(x)
86 w.Write(bytes)
87 case error:
88 encoder := json.NewEncoder(w)
89 _ = encoder.Encode(map[string]string{
90 "message": x.Error(),
91 })
92 default:
93 encoder := json.NewEncoder(w)
94 _ = encoder.Encode(x)
95 }
96}

Callers 2

EncodeErrorMethod · 0.85
EncodeResponseMethod · 0.85

Calls 10

HeaderMethod · 0.80
HeadersMethod · 0.80
WriteHeaderMethod · 0.80
EncodeMethod · 0.80
GetMethod · 0.65
StatusCodeMethod · 0.65
MarshalMethod · 0.65
SetMethod · 0.45
WriteMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected