orangesite/hn/server.go

130 lines
2.4 KiB
Go
Raw Normal View History

2020-03-24 20:32:35 +00:00
package hn
import (
"os"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
2020-03-25 00:49:19 +00:00
gl "github.com/labstack/gommon/log"
"github.com/mattn/go-isatty"
ep2 "github.com/mayowa/echo-pongo2"
2020-03-24 20:32:35 +00:00
"github.com/ziflex/lecho/v2"
2020-03-25 00:49:19 +00:00
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
2020-03-24 20:32:35 +00:00
type App struct {
version string
buildarch string
e *echo.Echo
2020-03-25 00:49:19 +00:00
log *zerolog.Logger
2020-03-24 20:32:35 +00:00
db *gorm.DB
startup time.Time
2020-03-25 00:49:19 +00:00
fetcher *Fetcher
2020-03-24 20:32:35 +00:00
}
func RunServer(version string, buildarch string) int {
a := new(App)
a.version = version
a.buildarch = buildarch
a.startup = time.Now()
2020-03-25 00:49:19 +00:00
a.init()
defer a.db.Close()
a.fetcher = NewFetcher(a.db)
a.fetcher.AddLogger(a.log)
go a.fetcher.run()
return a.runForever()
2020-03-24 20:32:35 +00:00
}
2020-03-25 00:49:19 +00:00
func (a *App) init() {
// setup logging
l := log.With().Caller().Logger()
log.Logger = l
tty := isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd())
if tty {
out := zerolog.NewConsoleWriter(
func(w *zerolog.ConsoleWriter) {
// Customize time format
w.TimeFormat = time.RFC3339
},
)
log.Logger = log.Output(out)
}
// always log in UTC
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if os.Getenv("DEBUG") != "" {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
a.log = &log.Logger
a.identify()
// open db
// FIXME make configurable path
db, err := gorm.Open("sqlite3", "storage.db")
if err != nil {
panic("failed to connect database")
}
a.db = db
}
func (a *App) identify() {
log.Info().
Str("version", a.version).
Str("buildarch", a.buildarch).
Msg("starting")
}
func (a *App) runForever() int {
2020-03-24 20:32:35 +00:00
// Echo instance
a.e = echo.New()
2020-03-25 00:49:19 +00:00
lev := gl.INFO
2020-03-24 20:32:35 +00:00
if os.Getenv("DEBUG") != "" {
2020-03-25 00:49:19 +00:00
lev = gl.DEBUG
2020-03-24 20:32:35 +00:00
}
logger := lecho.New(
os.Stdout,
lecho.WithLevel(lev),
lecho.WithTimestamp(),
lecho.WithCaller(),
)
a.e.Logger = logger
a.e.Use(middleware.RequestID())
// Middleware
a.e.Use(middleware.Logger())
a.e.Use(middleware.Recover())
2020-03-25 00:49:19 +00:00
r, err := ep2.NewRenderer("view")
if err != nil {
a.e.Logger.Fatal(err)
}
a.e.Renderer = r
2020-03-25 03:55:03 +00:00
rhs := NewRequestHandlerSet(a.db)
2020-03-24 20:32:35 +00:00
// Routes
2020-03-25 03:55:03 +00:00
a.e.GET("/", rhs.indexHandler)
a.e.GET("/about", rhs.aboutHandler)
2020-03-24 20:32:35 +00:00
// Start server
a.e.Logger.Fatal(a.e.Start(":8080"))
2020-03-25 00:49:19 +00:00
return 0 //FIXME setup graceful shutdown
2020-03-24 20:32:35 +00:00
}