-
Notifications
You must be signed in to change notification settings - Fork 0
/
defaults_codec.go.gen.go
7 lines (5 loc) · 2.68 KB
/
defaults_codec.go.gen.go
1
2
3
4
5
6
7
// AUTOMATICALLY GENERATED FILE. DO NOT EDIT.
package dispel
var defaultsCodec = gofmtTmpl(asset.init(asset{Name: "defaults_codec.go", Content: "" +
"// +build impl\n\npackage dispel\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"hash/fnv\"\n\t\"net/http\"\n)\n\n// JSONCodec represents a codec for http request decoding and response encoding using JSON.\n//\n// JSONCodec relies on encoding/json in its implementation.\ntype JSONCodec struct{}\n\nfunc handleEtag(w http.ResponseWriter, r *http.Request) (ok bool) {\n\tif r.Method != \"GET\" && r.Method != \"HEAD\" {\n\t\treturn\n\t}\n\tetag := w.Header().Get(\"Etag\")\n\tif etag == \"\" {\n\t\treturn\n\t}\n\tinm := r.Header.Get(\"If-None-Match\")\n\tif inm == \"\" {\n\t\treturn\n\t}\n\n\tif inm == etag || inm == \"*\" {\n\t\tw.Header().Del(\"Content-Type\")\n\t\tw.Header().Del(\"Content-Length\")\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\tok = true\n\t}\n\treturn\n}\n\nfunc makeEtag(b []byte) string {\n\th := fnv.New64a()\n\th.Write(b)\n\treturn `\"` + base64.StdEncoding.EncodeToString(h.Sum(nil)) + `\"`\n}\n\n// Encode implements the HTTPEncoder interface with JSON encoding.\n//\n// It writes to the response writer using\n// encoding/json.Marshal(), handles Etags, sets inconditionnally a \"application/json; charset=utf-8\" Content-Type header.\n// It skips writing a response body if any of the conditions are met:\n//\n// * the status code is [100, 200)\n// * the status code is http.StatusNoContent (204) or http.StatusNotModified (304)\n// * the request method is HEAD.\nfunc (j *JSONCodec) Encode(w http.ResponseWriter, r *http.Request, data interface{}, code int) error {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif w.Header().Get(\"ETag\") == \"\" {\n\t\tw.Header().Set(\"ETag\", makeEtag(b))\n\t}\n\tif code == 0 {\n\t\tcode = http.StatusOK\n\t}\n\n\tif code == http.StatusOK {\n\t\tif ok := handleEtag(w, r); ok {\n\t\t\treturn nil\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(code)\n\tswitch {\n\tcase code >= 100 && code <= 199:\n\t\treturn nil\n\tcase code == 204:\n\t\treturn nil\n\tcase code == 304:\n\t\treturn nil\n\tcase r.Method == \"HEAD\":\n\t\treturn nil\n\tdefault:\n\t\tif _, err := w.Write(b); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// Decode implements the HTTPDecoder interface with JSON decoding.\n//\n// It simply decodes the request body using json.NewDecoder() and closes it.\nfunc (j *JSONCodec) Decode(w http.ResponseWriter, r *http.Request, data interface{}) error {\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n" +
""}))