func TestRespond(t *testing.T) { h := func(w http.ResponseWriter, r *http.Request) { payload := SampleObjs{ []SampleObj{ {"foo", "bar"}, }, } jsonrespond.Respond(w, http.StatusOK, payload) } ts := setupServer(h) res, err := http.Get(ts.URL) if err != nil { t.Fatal(err) } // check the status if res.StatusCode != http.StatusOK { t.Error("expected status code %v, received %v", http.StatusOK, res.StatusCode) } // check the response output := &SampleObjs{} err = json.NewDecoder(res.Body).Decode(output) if err != nil { t.Fatal(err) } if output.Root[0].Key != "foo" || output.Root[0].Val != "bar" { t.Error("unexepected Response: %v", output) } }
// POST /signup // Params: username, email, password func Signup(w http.ResponseWriter, r *http.Request, c router.Context) error { db, ok := c.Meta["db"].(*sqlx.DB) if !ok { return errors.New("db not set in context") } username := r.FormValue("username") if username == "" { return res.BadRequest(w, res.ErrorMsg{"username_required", "username required"}) } email := r.FormValue("email") if email == "" { return res.BadRequest(w, res.ErrorMsg{"email_required", "email required"}) } password := r.FormValue("password") if password == "" { return res.BadRequest(w, res.ErrorMsg{"password_required", "password required"}) } u := &data.User{ Username: username, Email: email, } if err := u.EncryptPassword(password); err != nil { return err } if err := u.Insert(db); err != nil { if e, ok := err.(*data.Error); ok { return res.BadRequest(w, res.ErrorMsg{e.Code, e.Desc}) } return err } return res.Respond(w, http.StatusCreated, u) }