go-project-template/web/server.go

106 lines
2.3 KiB
Go
Raw Permalink Normal View History

2024-07-25 05:13:23 +00:00
package web
2024-05-05 22:10:32 +00:00
import (
"context"
"database/sql"
"errors"
"net/http"
"time"
2024-07-25 05:13:23 +00:00
"github.com/gorilla/sessions"
2024-05-05 22:10:32 +00:00
echo "github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
"git.janky.solutions/finn/go-project-template/config"
)
var server *echo.Echo
func ListenAndServe() {
2024-07-25 05:13:23 +00:00
sessionStore = sessions.NewCookieStore([]byte(config.C.Web.SessionKey))
2024-05-05 22:10:32 +00:00
server = echo.New()
server.HideBanner = true
server.HidePort = true
server.HTTPErrorHandler = handleError
server.Renderer = &Template{}
2024-07-25 05:13:23 +00:00
server.Use(accessLogMiddleware, sessionMiddleware)
2024-05-05 22:10:32 +00:00
server.RouteNotFound("/*", notFoundHandler)
2024-07-25 05:13:23 +00:00
server.GET("/auth/begin", authBegin)
server.GET("/auth/finish", authFinish)
server.GET("/", index, authMiddleware)
2024-05-05 22:10:32 +00:00
server.StaticFS("/static", Static)
2024-07-25 05:13:23 +00:00
logrus.WithField("address", config.C.Web.Bind).Info("starting http server")
err := server.Start(config.C.Web.Bind)
2024-05-05 22:10:32 +00:00
if err != http.ErrServerClosed {
logrus.WithError(err).Fatal("error starting http server")
}
}
func Shutdown(ctx context.Context) error {
if server == nil {
return nil
}
return server.Shutdown(ctx)
}
func accessLogMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
start := time.Now()
err := next(c)
log := logrus.WithFields(logrus.Fields{
"method": c.Request().Method,
"path": c.Request().URL.Path,
"duration": time.Since(start),
"status": c.Response().Status,
"source": c.Request().RemoteAddr,
})
if err != nil {
log = log.WithError(err)
}
log.Debug("request handled")
return err
}
}
func handleError(err error, c echo.Context) {
if errors.Is(err, sql.ErrNoRows) {
logrus.Debug("sending 404 because handler threw sql.ErrNoRows")
err = notFoundHandler(c)
if err == nil {
return
}
}
logrus.WithFields(logrus.Fields{
"path": c.Request().URL.Path,
"method": c.Request().Method,
"error": err,
}).Error("error handling request")
_ = c.Render(http.StatusNotFound, "500.html", nil)
}
func notFoundHandler(c echo.Context) error {
return c.Render(http.StatusNotFound, "404.html", nil)
}
2024-07-25 05:13:23 +00:00
func sessionMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session, err := sessionStore.Get(c.Request(), sessionName)
if err != nil {
return err
}
c.Set(contextKeySession, session)
return next(c)
}
}