/
server.go
81 lines (67 loc) · 1.86 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package server
import (
"context"
"errors"
"fmt"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/rs/zerolog"
"golang.org/x/crypto/acme/autocert"
"github.com/gaia-pipeline/gaia-bot/pkg/bot"
)
// Config is the configuration of the bot's main cycle.
type Config struct {
Port string
Hostname string
ServerKeyPath string
ServerCrtPath string
AutoTLS bool
CacheDir string
}
// GaiaBot is a server.
type GaiaBot struct {
Config
Dependencies
}
// Dependencies defines needed dependencies for this bot.
type Dependencies struct {
Bot bot.Bot
Logger zerolog.Logger
}
// Server defines a server which runs and accepts requests and monitors
// Gaia PRs.
type Server interface {
Run(context.Context) error
}
// NewServer creates a new gaia bot server.
func NewServer(cfg Config, deps Dependencies) *GaiaBot {
return &GaiaBot{Config: cfg, Dependencies: deps}
}
// Run starts up the listening for PR actions.
func (s *GaiaBot) Run(ctx context.Context) error {
s.Dependencies.Logger.Info().Msg("Start listening...")
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.POST("/hook", s.Dependencies.Bot.Hook(ctx))
hostPort := fmt.Sprintf("%s:%s", s.Config.Hostname, s.Config.Port)
// Start TLS with certificate paths
if len(s.Config.ServerKeyPath) > 0 && len(s.Config.ServerCrtPath) > 0 {
e.Pre(middleware.HTTPSRedirect())
return e.StartTLS(hostPort, s.Config.ServerCrtPath, s.Config.ServerKeyPath)
}
// Start Auto TLS server
if s.Config.AutoTLS {
if len(s.Config.CacheDir) < 1 {
return errors.New("cache dir must be provided if autoTLS is enabled")
}
e.Pre(middleware.HTTPSRedirect())
e.AutoTLSManager.Cache = autocert.DirCache(s.Config.CacheDir)
return e.StartAutoTLS(hostPort)
}
// Start regular server
return e.Start(hostPort)
}