github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/api/admin/api.go (about) 1 // Package admin ties together administration resources and handlers. 2 package admin 3 4 import ( 5 "net/http" 6 7 "github.com/sirupsen/logrus" 8 9 "github.com/go-chi/chi/v5" 10 "github.com/go-pg/pg" 11 12 "github.com/dhax/go-base/auth/authorize" 13 "github.com/dhax/go-base/database" 14 "github.com/dhax/go-base/logging" 15 ) 16 17 const ( 18 roleAdmin = "admin" 19 ) 20 21 type ctxKey int 22 23 const ( 24 ctxAccount ctxKey = iota 25 ) 26 27 // API provides admin application resources and handlers. 28 type API struct { 29 Accounts *AccountResource 30 } 31 32 // NewAPI configures and returns admin application API. 33 func NewAPI(db *pg.DB) (*API, error) { 34 35 accountStore := database.NewAdmAccountStore(db) 36 accounts := NewAccountResource(accountStore) 37 38 api := &API{ 39 Accounts: accounts, 40 } 41 return api, nil 42 } 43 44 // Router provides admin application routes. 45 func (a *API) Router() *chi.Mux { 46 r := chi.NewRouter() 47 r.Use(authorize.RequiresRole(roleAdmin)) 48 49 r.Get("/", func(w http.ResponseWriter, r *http.Request) { 50 w.Write([]byte("Hello Admin")) 51 }) 52 53 r.Mount("/accounts", a.Accounts.router()) 54 return r 55 } 56 57 func log(r *http.Request) logrus.FieldLogger { 58 return logging.GetLogEntry(r) 59 }