61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
|
package web
|
||
|
|
||
|
import (
|
||
|
"time"
|
||
|
|
||
|
packr "github.com/gobuffalo/packr/v2"
|
||
|
|
||
|
"code.chrissexton.org/cws/happy/email"
|
||
|
"github.com/speps/go-hashids"
|
||
|
|
||
|
"code.chrissexton.org/cws/happy/db"
|
||
|
"github.com/gorilla/mux"
|
||
|
"github.com/rs/zerolog/log"
|
||
|
"github.com/stretchr/graceful"
|
||
|
)
|
||
|
|
||
|
type Web struct {
|
||
|
addr string
|
||
|
assetPath string
|
||
|
db *db.Database
|
||
|
salt string
|
||
|
h *hashids.HashID
|
||
|
box *packr.Box
|
||
|
email *email.EMailClient
|
||
|
}
|
||
|
|
||
|
func New(addr, assetPath string, db *db.Database, salt string, h *hashids.HashID, box *packr.Box, email *email.EMailClient) *Web {
|
||
|
w := &Web{
|
||
|
addr: addr,
|
||
|
assetPath: assetPath,
|
||
|
db: db,
|
||
|
salt: salt,
|
||
|
h: h,
|
||
|
box: box,
|
||
|
email: email,
|
||
|
}
|
||
|
if err := db.MakeDB(); err != nil {
|
||
|
log.Fatal().
|
||
|
Err(err).
|
||
|
Msg("could not create database")
|
||
|
}
|
||
|
return w
|
||
|
}
|
||
|
|
||
|
func (web *Web) routeSetup() *mux.Router {
|
||
|
r := mux.NewRouter()
|
||
|
api := r.PathPrefix("/v1/").Subrouter()
|
||
|
api.HandleFunc("/moods", web.getMoods).Methods("GET")
|
||
|
api.HandleFunc("/moods", web.handleMood).Methods("POST")
|
||
|
api.HandleFunc("/user/code", web.handlerRegisterCode).Methods("GET")
|
||
|
api.HandleFunc("/user/info", web.checkUser).Methods("GET")
|
||
|
r.PathPrefix("/").HandlerFunc(web.indexHandler("/index.html"))
|
||
|
return r
|
||
|
}
|
||
|
|
||
|
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)
|
||
|
}
|