ResponseEncoder returns a HTTP response encoder leveraging the mime type set in the context under the AcceptTypeKey or the ContentTypeKey if any. The encoder supports the following mime types: - application/json using package encoding/json - application/xml using package encoding/xml - application/
(ctx context.Context, w http.ResponseWriter)
| 100 | // ContentTypeKey value does not match any of the supported mime types or is |
| 101 | // missing altogether. |
| 102 | func ResponseEncoder(ctx context.Context, w http.ResponseWriter) Encoder { |
| 103 | negotiate := func(a string) (Encoder, string) { |
| 104 | switch a { |
| 105 | case "", "application/json": |
| 106 | // default to JSON |
| 107 | return json.NewEncoder(w), "application/json" |
| 108 | case "application/xml": |
| 109 | return xml.NewEncoder(w), "application/xml" |
| 110 | case "application/gob": |
| 111 | return gob.NewEncoder(w), "application/gob" |
| 112 | case "text/html", "text/plain": |
| 113 | return newTextEncoder(w, a), a |
| 114 | } |
| 115 | return nil, "" |
| 116 | } |
| 117 | var accept string |
| 118 | { |
| 119 | if a := ctx.Value(AcceptTypeKey); a != nil { |
| 120 | accept = a.(string) |
| 121 | } |
| 122 | } |
| 123 | var ct string |
| 124 | { |
| 125 | if a := ctx.Value(ContentTypeKey); a != nil { |
| 126 | ct = a.(string) |
| 127 | } |
| 128 | } |
| 129 | var ( |
| 130 | enc Encoder |
| 131 | mt string |
| 132 | err error |
| 133 | ) |
| 134 | { |
| 135 | if ct != "" { |
| 136 | // If content type explicitly set in the DSL, infer the response encoder |
| 137 | // from the content type context key. |
| 138 | if mt, _, err = mime.ParseMediaType(ct); err == nil { |
| 139 | switch { |
| 140 | case mt == "application/json" || strings.HasSuffix(mt, "+json"): |
| 141 | enc = json.NewEncoder(w) |
| 142 | case mt == "application/xml" || strings.HasSuffix(mt, "+xml"): |
| 143 | enc = xml.NewEncoder(w) |
| 144 | case mt == "application/gob" || strings.HasSuffix(mt, "+gob"): |
| 145 | enc = gob.NewEncoder(w) |
| 146 | case mt == "text/html" || mt == "text/plain" || |
| 147 | strings.HasSuffix(mt, "+html") || strings.HasSuffix(mt, "+txt"): |
| 148 | enc = newTextEncoder(w, mt) |
| 149 | default: |
| 150 | enc = json.NewEncoder(w) |
| 151 | } |
| 152 | } |
| 153 | SetContentType(w, ct) |
| 154 | return enc |
| 155 | } |
| 156 | // If Accept header exists in the request, infer the response encoder |
| 157 | // from the header value. |
| 158 | if enc, mt = negotiate(accept); enc == nil { |
| 159 | // attempt to normalize |