// Handle serves an endpoint with the provided handler func (s *Subrouter) Handle(method string, path string, h http.Handler) { // calcular path fullPath := s.getFullPath(path) hrh := func(w http.ResponseWriter, req *http.Request, params map[string]string) { httpcontext.Set(req, paramsKey, params) s.Stack.Then(h).ServeHTTP(w, req) } s.router.Handle(method, fullPath, hrh) }
func with(w http.ResponseWriter, r *http.Request, status int, data interface{}, opts *Options, multiple bool) { hasOpts := opts != nil if hasOpts && multiple && !opts.AllowMultiple { panic("respond: multiple responses") } encoder := JSON // JSON by default if hasOpts { if opts.Before != nil { status, data = opts.Before(w, r, status, data) } if opts.Encoder != nil { encoder = opts.Encoder(w, r) } } // write response w.Header().Set("Content-Type", encoder.ContentType(w, r)) w.WriteHeader(status) if err := encoder.Encode(w, r, data); err != nil { if hasOpts && opts.OnErr != nil { opts.OnErr(err) } else { panic("respond: " + err.Error()) } } if hasOpts { if opts.After != nil { opts.After(w, r, status, data) } httpcontext.Set(r, RespondedKey, true) } }
func TestHandlerUSers(t *testing.T) { var err error login := "******" assert := assert.New(t) assert.NoError(scope.Init()) scope.Log, err = logger.New(ioutil.Discard, false) assert.NoError(err) // drop table users assert.NoError(scope.DB.DropTableIfExists(&core.User{}).Error) assert.NoError(scope.DB.AutoMigrate(&core.User{}).Error) // Get all users should return empty json array w := httptest.NewRecorder() r, _ := http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") usersGetAll(w, r) b, _ := ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.Equal("[]", string(b)) // Add user w = httptest.NewRecorder() r, _ = http.NewRequest("POST", "http://localhost/foobar", bytes.NewBufferString(`{"passwd": "passwd", "authRelay": true, "haveMailbox": true, "mailboxQuota": "1G"}`)) r.SetBasicAuth("admin", "admin") ps := httprouter.Params{ httprouter.Param{"user", login}, } httpcontext.Set(r, "params", ps) usersAdd(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(201, w.Code, string(b)) // Get users; should return one user w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") usersGetAll(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.NotEqual("[]", string(b)) u := core.User{} assert.NoError(json.NewDecoder(bytes.NewReader(b[1 : len(b)-1])).Decode(&u)) assert.Equal(login, u.Login) assert.Equal(true, u.AuthRelay) assert.Equal(true, u.HaveMailbox) assert.Equal("1G", u.MailboxQuota) // Get One users; should return one user w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") ps = httprouter.Params{ httprouter.Param{"user", login}, } httpcontext.Set(r, "params", ps) usersGetOne(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.NotEqual("[]", string(b)) u = core.User{} assert.NoError(json.NewDecoder(bytes.NewReader(b)).Decode(&u)) assert.Equal(login, u.Login) assert.Equal(true, u.AuthRelay) assert.Equal(true, u.HaveMailbox) assert.Equal("1G", u.MailboxQuota) // Del user w = httptest.NewRecorder() r, _ = http.NewRequest("DELETE", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") ps = httprouter.Params{ httprouter.Param{"user", login}, } httpcontext.Set(r, "params", ps) usersDel(w, r) assert.Equal(200, w.Code) }
func TestHandlerQueue(t *testing.T) { var err error assert := assert.New(t) assert.NoError(scope.Init()) scope.Log, err = logger.New(ioutil.Discard, false) assert.NoError(err) // drop table queue assert.NoError(scope.DB.DropTableIfExists(&core.QMessage{}).Error) assert.NoError(scope.DB.AutoMigrate(&core.QMessage{}).Error) // Get all message in queue should return empty json array w := httptest.NewRecorder() r, _ := http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") queueGetMessages(w, r) b, _ := ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.Equal("[]", string(b)) // Add message message := core.QMessage{ Uuid: "uuid", Key: "key", AddedAt: time.Now(), Status: 2, DeliveryFailedCount: 0, } assert.NoError(scope.DB.Create(&message).Error) // Get all message w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") queueGetMessages(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.NotEqual("[]", string(b)) m := core.QMessage{} assert.NoError(json.NewDecoder(bytes.NewReader(b[1 : len(b)-1])).Decode(&m)) assert.Equal(m.Uuid, "uuid") // Get one w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") ps := httprouter.Params{ httprouter.Param{"id", fmt.Sprintf("%d", m.Id)}, } httpcontext.Set(r, "params", ps) queueGetMessage(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) assert.NotEqual("[]", string(b)) m = core.QMessage{} assert.NoError(json.NewDecoder(bytes.NewReader(b)).Decode(&m)) assert.Equal(m.Uuid, "uuid") // discard w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") ps = httprouter.Params{ httprouter.Param{"id", fmt.Sprintf("%d", m.Id)}, } httpcontext.Set(r, "params", ps) queueDiscardMessage(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) // bounce w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "http://localhost/foobar", nil) r.SetBasicAuth("admin", "admin") ps = httprouter.Params{ httprouter.Param{"id", fmt.Sprintf("%d", m.Id)}, } httpcontext.Set(r, "params", ps) queueBounceMessage(w, r) b, _ = ioutil.ReadAll(w.Body) assert.Equal(200, w.Code, string(b)) }
// wrapHandler puts httprouter.Params in query context // in order to keep compatibily with http.Handler func wrapHandler(h func(http.ResponseWriter, *http.Request)) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { httpcontext.Set(r, "params", ps) h(w, r) } }
func setParams(r *http.Request, val map[string]string) { httpcontext.Set(r, paramsKey, val) }
func wrap(handler http.Handler) httprouter.Handle { return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { httpcontext.Set(req, paramsKey, params) handler.ServeHTTP(w, req) } }
func (o *Options) ServeHTTP(w http.ResponseWriter, r *http.Request) { httpcontext.Set(r, OptionsKey, o) }
// Handler wraps an HTTP handler becoming the source of options for all // containing With calls. func (o *Options) Handler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpcontext.Set(r, OptionsKey, o) handler.ServeHTTP(w, r) }) }