cabinet/web/routes.go

60 lines
1.4 KiB
Go
Raw Normal View History

2019-10-30 15:31:07 +00:00
package web
import (
2019-11-01 17:09:17 +00:00
"net/http"
"os"
2019-10-30 15:31:07 +00:00
"time"
2019-10-30 20:19:35 +00:00
"code.chrissexton.org/cws/cabinet/db"
2019-10-30 15:31:07 +00:00
packr "github.com/gobuffalo/packr/v2"
"github.com/speps/go-hashids"
"github.com/gorilla/mux"
2019-11-01 17:09:17 +00:00
"github.com/gorilla/handlers"
2019-10-30 15:31:07 +00:00
"github.com/rs/zerolog/log"
"github.com/stretchr/graceful"
)
type Web struct {
addr string
db *db.Database
salt string
h *hashids.HashID
box *packr.Box
}
2019-10-31 15:14:11 +00:00
func New(addr string, db *db.Database, box *packr.Box) *Web {
2019-10-30 15:31:07 +00:00
w := &Web{
addr: addr,
db: db,
box: box,
}
if err := db.MakeDB(); err != nil {
log.Fatal().
Err(err).
Msg("could not create database")
}
return w
}
2019-11-01 17:09:17 +00:00
func (web *Web) routeSetup() http.Handler {
2019-10-30 15:31:07 +00:00
r := mux.NewRouter()
2019-11-03 20:01:24 +00:00
api := r.PathPrefix("/v1/").Subrouter()
api.HandleFunc("/entries", web.allEntries).Methods(http.MethodGet)
api.HandleFunc("/entries", web.newEntry).Methods(http.MethodPost)
api.HandleFunc("/entries", web.removeEntry).Methods(http.MethodDelete)
api.HandleFunc("/entries/{slug}", web.editEntry).Methods(http.MethodPut)
api.HandleFunc("/entries/{slug}", web.getEntry).Methods(http.MethodGet)
2019-10-30 15:31:07 +00:00
r.PathPrefix("/").HandlerFunc(web.indexHandler("/index.html"))
2019-11-01 17:09:17 +00:00
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
return loggedRouter
2019-10-30 15:31:07 +00:00
}
func (web *Web) Serve() {
middle := web.routeSetup()
log.Info().Str("addr", "http://"+web.addr).Msg("serving HTTP")
graceful.Run(web.addr, 10*time.Second, middle)
}