60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package web
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi"
|
|
"github.com/gobuffalo/packr/v2"
|
|
"github.com/ollien/updown/handler/paste"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// Webserver is the main websever
|
|
type Webserver struct {
|
|
httpServer *http.Server
|
|
router chi.Router
|
|
logger *logrus.Logger
|
|
logWriter *io.PipeWriter // used for httpServer.ErrorLog. Must be stored separately so we can close it.
|
|
pasteService *paste.Service
|
|
staticFiles http.FileSystem
|
|
templates *packr.Box
|
|
}
|
|
|
|
// NewWebserver creates a new webserver and sets up all routes
|
|
func NewWebserver() *Webserver {
|
|
server := initWebserver()
|
|
server.setupRoutes()
|
|
|
|
return server
|
|
}
|
|
|
|
// Start starts the webserver
|
|
func (server *Webserver) Start() error {
|
|
defer server.logWriter.Close()
|
|
return server.httpServer.ListenAndServe()
|
|
}
|
|
|
|
func (server *Webserver) setupRoutes() {
|
|
router := server.router
|
|
router.Get("/", server.index)
|
|
router.Route("/paste", func(r chi.Router) {
|
|
r.Post("/", server.makePaste)
|
|
r.Get(`/{handle:[a-zA-Z0-9-]+}`, server.getPaste)
|
|
})
|
|
router.Get("/static/*", http.StripPrefix("/static", http.FileServer(server.staticFiles)).ServeHTTP)
|
|
}
|
|
|
|
func (server *Webserver) log(level logrus.Level, req *http.Request, message interface{}) {
|
|
server.logExtra(level, req, message, nil)
|
|
}
|
|
|
|
func (server *Webserver) logExtra(level logrus.Level, req *http.Request, message interface{}, extra logrus.Fields) {
|
|
if extra == nil {
|
|
extra = make(logrus.Fields, 1)
|
|
}
|
|
extra["route"] = req.RequestURI
|
|
entry := server.logger.WithFields(extra)
|
|
entry.Log(level, message)
|
|
}
|