feta/process/server.go

114 lines
2.2 KiB
Go
Raw Normal View History

2019-12-19 14:24:26 +00:00
package process
2019-11-02 06:56:17 +00:00
import (
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
gl "github.com/labstack/gommon/log"
ep2 "github.com/mayowa/echo-pongo2"
"github.com/ziflex/lecho"
//"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/rs/zerolog/log"
)
2019-11-02 06:56:17 +00:00
2019-12-19 14:24:26 +00:00
// Server is the HTTP webserver object
type Server struct {
feta *Feta
port uint
e *echo.Echo
router *gin.Engine
httpserver *http.Server
debug bool
db *gorm.DB
2019-11-02 06:56:17 +00:00
}
2019-12-19 14:24:26 +00:00
// SetFeta tells the http Server where to find the Process object so that it
// can pull stats and other information for serving via http
func (a *Server) SetFeta(feta *Feta) {
a.feta = feta
2019-11-05 02:57:48 +00:00
}
2019-12-19 14:24:26 +00:00
// Serve is the entrypoint for the Server, which should run in its own
// goroutine (started by the Process)
func (a *Server) Serve() {
2019-11-06 01:15:31 +00:00
if a.feta == nil {
panic("must have feta app from which to serve stats")
2019-11-02 06:56:17 +00:00
}
2019-11-09 06:13:19 +00:00
if os.Getenv("DEBUG") != "" {
a.debug = true
}
a.port = 8080
if os.Getenv("PORT") != "" {
s, err := strconv.ParseUint(os.Getenv("PORT"), 10, 64)
if err != nil {
a.port = uint(s)
}
}
a.initRouter()
a.initServer()
a.e.Logger.Fatal(a.e.StartServer(a.httpserver))
2019-11-02 06:56:17 +00:00
}
func (s *Server) initRouter() {
2019-11-02 06:56:17 +00:00
// Echo instance
s.e = echo.New()
2019-11-02 06:56:17 +00:00
s.e.HideBanner = true
2019-11-02 06:56:17 +00:00
lev := gl.INFO
if os.Getenv("DEBUG") != "" {
lev = gl.DEBUG
}
2019-11-02 06:56:17 +00:00
logger := lecho.New(
os.Stdout,
lecho.WithLevel(lev),
lecho.WithTimestamp(),
lecho.WithCaller(),
)
s.e.Logger = logger
s.e.Use(middleware.RequestID())
2019-11-02 06:56:17 +00:00
// Middleware
s.e.Use(middleware.Logger())
s.e.Use(middleware.Recover())
2019-11-02 06:56:17 +00:00
r, err := ep2.NewRenderer("view")
if err != nil {
s.e.Logger.Fatal(err)
2019-11-02 06:56:17 +00:00
}
s.e.Renderer = r
// Routes
s.e.GET("/", s.indexHandler)
s.e.GET("/stats.json", s.statsHandler)
s.e.GET("/.well-known/healthcheck.json", s.healthCheckHandler)
//a.e.GET("/about", s.aboutHandler)
}
2019-11-02 06:56:17 +00:00
func (s *Server) initServer() {
log.Info().Uint("port", s.port).Msg("starting webserver")
2019-11-02 06:56:17 +00:00
s.httpserver = &http.Server{
Addr: fmt.Sprintf(":%d", s.port),
2019-11-02 06:56:17 +00:00
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}