-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
107 lines (91 loc) · 2.45 KB
/
Copy pathserver.go
File metadata and controls
107 lines (91 loc) · 2.45 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package http
import (
"context"
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/neuronlabs/neuron-extensions/server/http/log"
"github.com/neuronlabs/neuron/server"
)
var _ server.Server = &Server{}
// API is an interface used for the server API's.
type API interface {
server.EndpointsGetter
InitializeAPI(options server.Options) error
SetRoutes(router *httprouter.Router) error
}
// Server is an http server implementation. It implements neuron/server.Server interface.
type Server struct {
Options *Options
Router *httprouter.Router
Endpoints []*server.Endpoint
serverOptions server.Options
server http.Server
}
// New creates new server.
func New(options ...Option) *Server {
s := &Server{
Options: newOptions(),
server: http.Server{},
Router: httprouter.New(),
}
for _, option := range options {
option(s.Options)
}
return s
}
func newOptions() *Options {
return &Options{VersionedAPIs: map[string][]API{}}
}
// GetEndpoints gets all stored server endpoints.
func (s *Server) GetEndpoints() []*server.Endpoint {
return s.Endpoints
}
// Initialize initializes server with provided options.
func (s *Server) Initialize(options server.Options) error {
// Initialize all endpoints.
s.serverOptions = options
s.setOptions()
for _, api := range s.Options.APIs {
if err := api.InitializeAPI(options); err != nil {
return err
}
if err := api.SetRoutes(s.Router); err != nil {
return err
}
s.Endpoints = append(s.Endpoints, api.GetEndpoints()...)
}
for _, apis := range s.Options.VersionedAPIs {
for _, api := range apis {
if err := api.InitializeAPI(options); err != nil {
return err
}
if err := api.SetRoutes(s.Router); err != nil {
return err
}
s.Endpoints = append(s.Endpoints, api.GetEndpoints()...)
}
}
return nil
}
// Serve serves all routes stored in given server.
func (s *Server) Serve() error {
s.server.Handler = s.Router
log.Infof("Listening and serve at: %s:%d", s.Options.Hostname, s.Options.Port)
return s.server.ListenAndServe()
}
// Shutdown gently shutdown the server connection.
func (s *Server) Shutdown(ctx context.Context) error {
if err := s.server.Shutdown(ctx); err != nil {
log.Errorf("HTTP server shutdown failed: %v", err)
return err
}
return nil
}
func (s *Server) setOptions() {
if s.Options.Port == 0 {
s.Options.Port = 80
}
s.server.Addr = fmt.Sprintf("%s:%d", s.Options.Hostname, s.Options.Port)
s.server.TLSConfig = s.Options.TLSConfig
}