gowiki/pkg/server/server.go
2018-09-12 00:37:13 +02:00

81 lines
1.5 KiB
Go

package server
import (
"context"
"github.com/gorilla/mux"
"html/template"
"net"
"net/http"
"time"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/jwt"
)
const (
cookieName = "gosession"
)
type HTTPServer struct {
Version string
listener net.Listener
srv *http.Server
DB *db.DB
JWT *jwt.JWT
templ map[string]*template.Template
res map[string][]byte
}
func NewHTTPServer(l net.Listener, versin string, secCookie bool) (srv *HTTPServer) {
srv = &HTTPServer{
Version: version,
SecCookie: secCookie,
listener: l,
JWT: jwt.New(time.Hour*12, nil, nil),
}
srv.cookieStore()
srv.loadTemplates()
srv.srv = &http.Server{
Handler: srv.buildRoutes(),
}
return
}
func (s *HTTPServer) Start() (err error) {
s.DB, err = db.New()
if err != nil {
return
}
s.Index, err = NewIndex(blevePath)
if err != nil {
return
}
go func() {
log.Println(s.srv.Serve(s.listener))
}()
return
}
func (s *HTTPServer) Stop() error {
s.BS.Close()
s.Index.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return s.srv.Shutdown(ctx)
}
func (s *HTTPServer) buildRoutes() http.Handler {
m := mux.NewRouter()
m.NotFoundHandler = &notFoundHandler{s}
for _, v := range routes {
m.HandleFunc(v.Path, s.contextWrapper(v.Handler)).Methods(v.Methods...)
}
return m
}
func (s *HTTPServer) contextWrapper(h ctxHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h(newContext(w, r, s))
}
}