golang-lib/web/main.go

76 lines
1.8 KiB
Go
Raw Normal View History

2021-07-19 17:59:47 +02:00
/*
Package web implements common functionality for web APIs using Gin and Gorm.
Modules
Modules provide functionality for a web server. A module is a function executed
before starting a server, accessing the Service and the Gin Engine. Each Service
maintains a list of modules. When it runs, it executes all of its modules.
*/
2021-06-01 10:51:35 +02:00
package web
import (
"github.com/bdlm/log"
"github.com/gin-gonic/gin"
2021-06-01 10:51:35 +02:00
// acme
"github.com/gin-gonic/autotls"
"golang.org/x/crypto/acme/autocert"
2021-06-21 16:30:34 +02:00
// internal
"dev.sum7.eu/genofire/golang-lib/mailer"
"gorm.io/gorm"
2021-06-01 10:51:35 +02:00
)
2021-07-19 17:59:47 +02:00
// A Service stores configuration of a server.
2021-06-01 10:51:35 +02:00
type Service struct {
// config
Listen string `toml:"listen"`
AccessLog bool `toml:"access_log"`
Webroot string `toml:"webroot"`
ACME struct {
Enable bool `toml:"enable"`
Domains []string `toml:"domains"`
Cache string `toml:"cache"`
} `toml:"acme"`
Session struct {
Name string `toml:"name"`
Secret string `toml:"secret"`
} `toml:"session"`
// internal
2021-06-21 16:30:34 +02:00
DB *gorm.DB `toml:"-"`
Mailer *mailer.Service `toml:"-"`
modules []ModuleRegisterFunc
2021-06-01 10:51:35 +02:00
}
2021-07-19 17:59:47 +02:00
// Run creates, configures, and runs a new gin.Engine using its registered
// modules.
func (s *Service) Run() error {
2021-06-01 10:51:35 +02:00
gin.EnableJsonDecoderDisallowUnknownFields()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// catch crashed
r.Use(gin.Recovery())
2021-07-19 17:59:47 +02:00
if s.AccessLog {
2021-06-01 10:51:35 +02:00
r.Use(gin.Logger())
log.Debug("request logging enabled")
}
2021-07-19 17:59:47 +02:00
s.LoadSession(r)
s.Bind(r)
2021-06-01 10:51:35 +02:00
2021-07-19 17:59:47 +02:00
if s.ACME.Enable {
if s.Listen != "" {
2021-06-01 10:51:35 +02:00
log.Panic("For ACME / Let's Encrypt it is not possible to set `listen`")
}
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
2021-07-19 17:59:47 +02:00
HostPolicy: autocert.HostWhitelist(s.ACME.Domains...),
Cache: autocert.DirCache(s.ACME.Cache),
2021-06-01 10:51:35 +02:00
}
return autotls.RunWithManager(r, &m)
}
2021-07-19 17:59:47 +02:00
return r.Run(s.Listen)
2021-06-01 10:51:35 +02:00
}