-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathapi.go
80 lines (70 loc) · 1.55 KB
/
api.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
package worker
import (
"context"
"fmt"
"syscall"
"net/http"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/runabol/tork"
"github.com/runabol/tork/internal/httpx"
"github.com/runabol/tork/mq"
"github.com/runabol/tork/runtime"
)
const (
MIN_PORT = 8001
MAX_PORT = 8100
)
type api struct {
server *http.Server
broker mq.Broker
runtime runtime.Runtime
}
func newAPI(cfg Config) *api {
r := echo.New()
s := &api{
runtime: cfg.Runtime,
broker: cfg.Broker,
server: &http.Server{
Addr: cfg.Address,
Handler: r,
},
}
r.GET("/health", s.health)
return s
}
func (s *api) health(c echo.Context) error {
var status = "UP"
if err := s.runtime.HealthCheck(c.Request().Context()); err != nil {
status = "DOWN"
}
return c.JSON(http.StatusOK, map[string]string{
"status": status,
"version": fmt.Sprintf("%s (%s)", tork.Version, tork.GitCommit),
})
}
func (s *api) start() error {
if s.server.Addr != "" {
if err := httpx.StartAsync(s.server); err != nil {
return err
}
} else {
// attempting to dynamically assign port
for port := MIN_PORT; port <= MAX_PORT; port++ {
s.server.Addr = fmt.Sprintf("localhost:%d", port)
if err := httpx.StartAsync(s.server); err != nil {
if errors.Is(err, syscall.EADDRINUSE) {
continue
}
log.Fatal().Err(err).Msgf("error starting up server")
}
break
}
}
log.Info().Msgf("Worker listening on http://%s", s.server.Addr)
return nil
}
func (s *api) shutdown(ctx context.Context) error {
return s.server.Shutdown(ctx)
}