forked from foundation-go/foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_server.go
More file actions
78 lines (62 loc) · 1.82 KB
/
http_server.go
File metadata and controls
78 lines (62 loc) · 1.82 KB
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
package foundation
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/getsentry/sentry-go"
)
// HTTPServer represents a HTTP Server mode Foundation service.
type HTTPServer struct {
*Service
Options *HTTPServerOptions
}
// InitHTTPServer initializes a new Foundation service in HTTP Server mode.
func InitHTTPServer(name string) *HTTPServer {
return &HTTPServer{
Init(name),
NewHTTPServerOptions(),
}
}
// HTTPServerOptions are the options to start a Foundation service in HTTP Server mode.
type HTTPServerOptions struct {
// Handler is the HTTP handler to use.
Handler http.Handler
// StartComponentsOptions are the options to start the components.
StartComponentsOptions []StartComponentsOption
}
func NewHTTPServerOptions() *HTTPServerOptions {
return &HTTPServerOptions{}
}
// Start runs the Foundation service in HTTP Server mode.
func (s *HTTPServer) Start(opts *HTTPServerOptions) {
s.Options = opts
s.Service.Start(&StartOptions{
ModeName: "http_server",
StartComponentsOptions: s.Options.StartComponentsOptions,
ServiceFunc: s.ServiceFunc,
})
}
func (s *HTTPServer) ServiceFunc(ctx context.Context) error {
port := GetEnvOrInt("PORT", 51051)
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: s.Options.Handler,
}
s.Logger.Infof("Listening on http://0.0.0.0:%d", port)
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
err = fmt.Errorf("failed to start HTTP server: %w", err)
sentry.CaptureException(err)
s.Logger.Fatal(err)
}
}()
<-ctx.Done()
// Gracefully stop the HTTP server
if err := server.Shutdown(context.Background()); err != nil {
err = fmt.Errorf("failed to gracefully shutdown HTTP server: %w", err)
sentry.CaptureException(err)
s.Logger.Fatal(err)
}
return nil
}