func (h Employee) Create(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { var emp entity.Employee if err := jsonapi.UnmarshalPayload(r.Body, &emp); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } h.Repo.Save(emp) w.Header().Set("Content-Type", "application/vnd.api+json") w.WriteHeader(http.StatusCreated) }
func createBlog(w http.ResponseWriter, r *http.Request) { blog := new(Blog) if err := jsonapi.UnmarshalPayload(r.Body, blog); err != nil { http.Error(w, err.Error(), 500) return } // ...do stuff with your blog ... w.WriteHeader(201) w.Header().Set("Content-Type", "application/vnd.api+json") if err := jsonapi.MarshalOnePayload(w, blog); err != nil { http.Error(w, err.Error(), 500) } }
func exerciseHandler() { req, _ := http.NewRequest("GET", "/blogs", nil) req.Header.Set("Accept", "application/vnd.api+json") w := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(w, req) buf := new(bytes.Buffer) io.Copy(buf, w.Body) fmt.Println("============ jsonapi response from list ===========\n") fmt.Println(buf.String()) fmt.Println("============== end raw jsonapi from list =============") blog := testBlogForCreate(1) in := bytes.NewBuffer(nil) jsonapi.MarshalOnePayloadEmbedded(in, blog) req, _ = http.NewRequest("POST", "/blogs", in) req.Header.Set("Accept", "application/vnd.api+json") w = httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(w, req) buf = new(bytes.Buffer) io.Copy(buf, w.Body) fmt.Println("\n============ jsonapi response from create ===========\n") fmt.Println(buf.String()) fmt.Println("============== end raw jsonapi response =============") responseBlog := new(Blog) jsonapi.UnmarshalPayload(buf, responseBlog) out := bytes.NewBuffer(nil) json.NewEncoder(out).Encode(responseBlog) fmt.Println("\n================ Viola! Converted back our Blog struct =================\n") fmt.Printf("%s\n", out.Bytes()) fmt.Println("================ end marshal materialized Blog struct =================") }