func Auth(db *bolt.DB, lg quimby.Logger, name string) alice.Constructor { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { pth := req.URL.Path if pth == "/api/login" || strings.Index(pth, "/css") == 0 || strings.Index(pth, "/login.html") == 0 { h.ServeHTTP(w, req) return } f := quimby.GetUserFromCookie if len(req.Header.Get("Authorization")) > 0 { f = quimby.GetUserFromToken } user, err := f(req) if err != nil { if strings.Index(pth, "/api") > -1 { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("Not Authorized")) } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusMovedPermanently) } return } user.SetDB(db) if err := user.Fetch(); err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("Internal server error")) return } user.HashedPassword = []byte{} args := &Args{ User: user, DB: db, LG: lg, Vars: rex.Vars(req, name), Args: req.URL.Query(), } setArgs(req, args) h.ServeHTTP(w, req) context.Clear(req) }) } }
func (s *Server) deviceValue(w http.ResponseWriter, r *http.Request) { vars := rex.Vars(r, "main") k := fmt.Sprintf("%s %s", vars["location"], vars["device"]) s.statusLock.Lock() m, ok := s.updates[k] s.statusLock.Unlock() if !ok { w.WriteHeader(http.StatusNotFound) return } enc := json.NewEncoder(w) if err := enc.Encode(m.Value); err != nil { w.WriteHeader(http.StatusInternalServerError) } }
var err error req, err = http.NewRequest("GET", "/pals/1/pets/5?alive=true", nil) Expect(err).To(BeNil()) r.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) Expect(w.Body.String()).To(Equal("pet")) }) It("gets the colors collection", func() { var err error req, err = http.NewRequest("GET", "/pals/1/colors", nil) Expect(err).To(BeNil()) r.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) Expect(w.Body.String()).To(Equal("colors")) vars := rex.Vars(req, "my router") Expect(vars["id"]).To(Equal("1")) }) It("gets a colors resource", func() { var err error req, err = http.NewRequest("GET", "/pals/3/colors/red", nil) Expect(err).To(BeNil()) r.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) Expect(w.Body.String()).To(Equal("color")) vars := rex.Vars(req, "my router") Expect(vars["id"]).To(Equal("3")) Expect(vars["color"]).To(Equal("red")) })