github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/registry/regserver/handlers/handlers.go (about) 1 // Package handlers creates HTTP handler functions for registry interface implementations 2 package handlers 3 4 import ( 5 "net/http" 6 "time" 7 8 "github.com/gorilla/mux" 9 "github.com/qri-io/qri/registry" 10 "github.com/sirupsen/logrus" 11 ) 12 13 var ( 14 // logger 15 log = logrus.New() 16 ) 17 18 // SetLogLevel controls how detailed handler logging is 19 func SetLogLevel(level string) error { 20 lvl, err := logrus.ParseLevel(level) 21 if err != nil { 22 return err 23 } 24 log.SetLevel(lvl) 25 return nil 26 } 27 28 // RouteOptions defines configuration details for NewRoutes 29 type RouteOptions struct { 30 Protector MethodProtector 31 } 32 33 // AddProtector creates a configuration func for passing to NewRoutes 34 func AddProtector(p MethodProtector) func(o *RouteOptions) { 35 return func(o *RouteOptions) { 36 o.Protector = p 37 } 38 } 39 40 // NewRoutes allocates server handlers along standard routes 41 func NewRoutes(reg registry.Registry, opts ...func(o *RouteOptions)) *mux.Router { 42 o := &RouteOptions{ 43 Protector: NoopProtector(0), 44 } 45 for _, opt := range opts { 46 opt(o) 47 } 48 49 pro := o.Protector 50 m := mux.NewRouter() 51 m.HandleFunc("/health", HealthCheckHandler) 52 53 if rem := reg.Remote; rem != nil { 54 // add any "/remote" routes this remote provides 55 rem.AddDefaultRoutes(m) 56 } 57 58 if ps := reg.Profiles; ps != nil { 59 m.HandleFunc("/registry/profile", logReq(NewProfileHandler(ps))) 60 m.HandleFunc("/registry/profiles", pro.ProtectMethods("POST")(logReq(NewProfilesHandler(ps)))) 61 m.HandleFunc("/registry/provekey", NewProveKeyHandler(ps)) 62 } 63 64 if s := reg.Search; s != nil { 65 m.HandleFunc("/registry/search", logReq(NewSearchHandler(s))) 66 } 67 68 return m 69 } 70 71 func logReq(h http.HandlerFunc) http.HandlerFunc { 72 return func(w http.ResponseWriter, r *http.Request) { 73 log.Infof("%s %s %s", time.Now().Format(time.RFC3339), r.Method, r.URL.Path) 74 h.ServeHTTP(w, r) 75 } 76 } 77 78 // HealthCheckHandler is a basic "hey I'm fine" for load balancers & co 79 func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { 80 w.Header().Set("Content-Type", "application/json") 81 w.WriteHeader(http.StatusOK) 82 w.Write([]byte(`{"meta":{"code": 200,"status":"ok"},"data":null}`)) 83 }