error-pages/internal/http/server.go

80 lines
2.4 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
package http
import (
"strconv"
"time"
"github.com/fasthttp/router"
"github.com/tarampampam/error-pages/internal/checkers"
"github.com/tarampampam/error-pages/internal/http/common"
errorpageHandler "github.com/tarampampam/error-pages/internal/http/handlers/errorpage"
healthzHandler "github.com/tarampampam/error-pages/internal/http/handlers/healthz"
2021-10-06 17:38:00 +00:00
indexHandler "github.com/tarampampam/error-pages/internal/http/handlers/index"
notfoundHandler "github.com/tarampampam/error-pages/internal/http/handlers/notfound"
2021-09-29 15:38:50 +00:00
versionHandler "github.com/tarampampam/error-pages/internal/http/handlers/version"
"github.com/tarampampam/error-pages/internal/version"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
)
type Server struct {
fast *fasthttp.Server
router *router.Router
}
const (
2021-10-06 17:38:00 +00:00
defaultWriteTimeout = time.Second * 4
defaultReadTimeout = time.Second * 4
defaultIdleTimeout = time.Second * 6
2021-09-29 15:38:50 +00:00
)
func NewServer(log *zap.Logger) Server {
r := router.New()
return Server{
// fasthttp docs: <https://github.com/valyala/fasthttp>
fast: &fasthttp.Server{
WriteTimeout: defaultWriteTimeout,
ReadTimeout: defaultReadTimeout,
IdleTimeout: defaultIdleTimeout,
Handler: common.LogRequest(r.Handler, log),
NoDefaultServerHeader: true,
ReduceMemoryUsage: true,
CloseOnShutdown: true,
Logger: zap.NewStdLog(log),
},
router: r,
}
}
// Start server.
func (s *Server) Start(ip string, port uint16) error {
return s.fast.ListenAndServe(ip + ":" + strconv.Itoa(int(port)))
}
2021-10-06 17:38:00 +00:00
type (
errorsPager interface {
// GetPage with passed template name and error code.
GetPage(templateName, code string) ([]byte, error)
}
2021-09-29 15:38:50 +00:00
2021-10-06 17:38:00 +00:00
templatePicker interface {
// Pick the template name for responding.
Pick() string
2021-09-29 15:38:50 +00:00
}
2021-10-06 17:38:00 +00:00
)
2021-09-29 15:38:50 +00:00
2021-10-06 17:38:00 +00:00
// Register server routes, middlewares, etc.
// Router docs: <https://github.com/fasthttp/router>
func (s *Server) Register(errorsPager errorsPager, templatePicker templatePicker, defaultPageCode string) {
s.router.GET("/", indexHandler.NewHandler(errorsPager, templatePicker, defaultPageCode))
2021-09-29 15:38:50 +00:00
s.router.GET("/version", versionHandler.NewHandler(version.Version()))
s.router.ANY("/health/live", healthzHandler.NewHandler(checkers.NewLiveChecker()))
2021-10-06 17:38:00 +00:00
s.router.GET("/{code}.html", errorpageHandler.NewHandler(errorsPager, templatePicker))
2021-09-29 15:38:50 +00:00
2021-10-06 17:38:00 +00:00
s.router.NotFound = notfoundHandler.NewHandler()
2021-09-29 15:38:50 +00:00
}
// Stop server.
2021-10-06 17:38:00 +00:00
func (s *Server) Stop() error { return s.fast.Shutdown() }