func (doc *document) UnmarshalJSON(data []byte) error { //need to identify doc first if doc.ID == "" { base.Warn("Doc was unmarshaled without ID set") // TO DO: may be panic not required } //fetch json into doc.body err := json.Unmarshal([]byte(data), &doc.body) if err != nil { base.Warn("Error unmarshaling body of doc %q: %s", doc.ID, err) return err } return nil }
func (h *handler) addJSON(value interface{}) { encoder := json.NewEncoder(h.response) err := encoder.Encode(value) if err != nil { base.Warn("Couldn't serialize JSON for %v : %s", value, err) panic("JSON serialization failed") } }
// Writes an object to the response in JSON format. // If status is nonzero, the header will be written with that status. func (h *handler) writeJSONStatus(status int, value interface{}) { if !h.requestAccepts("application/json") { base.Warn("Client won't accept JSON, only %s", h.rq.Header.Get("Accept")) h.writeStatus(http.StatusNotAcceptable, "only application/json available") return } jsonOut, err := json.Marshal(value) if err != nil { base.Warn("Couldn't serialize JSON for %v : %s", value, err) h.writeStatus(http.StatusInternalServerError, "JSON serialization failed") return } if PrettyPrint { var buffer bytes.Buffer json.Indent(&buffer, jsonOut, "", " ") jsonOut = append(buffer.Bytes(), '\n') } h.setHeader("Content-Type", "application/json") if h.rq.Method != "HEAD" { //if len(jsonOut) < 1000 { // h.disableResponseCompression() //} h.setHeader("Content-Length", fmt.Sprintf("%d", len(jsonOut))) if status > 0 { h.response.WriteHeader(status) h.setStatus(status, "") } h.response.Write(jsonOut) } else if status > 0 { h.response.WriteHeader(status) h.setStatus(status, "") } }
// Parses a JSON request body into a custom structure. func (h *handler) readJSONInto(into interface{}) error { contentType := h.rq.Header.Get("Content-Type") if contentType != "" && !strings.HasPrefix(contentType, "application/json") { return base.HTTPErrorf(http.StatusUnsupportedMediaType, "Invalid content type %s", contentType) } //TO DO: zip version to be added decoder := json.NewDecoder(h.requestBody) if err := decoder.Decode(into); err != nil { base.Warn("Couldn't parse JSON in HTTP request: %v", err) return base.HTTPErrorf(http.StatusBadRequest, "Bad JSON") } return nil }