-
Notifications
You must be signed in to change notification settings - Fork 18
/
server.go
94 lines (76 loc) · 2.05 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
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"github.com/urfave/cli"
)
// Server that serves kuberdbs web service
type Server struct {
port int
version string
engine *gin.Engine
consul *Consul
}
type ServerConfig struct {
port int
consulDatacenter string
consulHTTPAddr string
consulACLToken string
consulScheme string
consulAllowStale bool
}
func NewServer(config *ServerConfig) (*Server, error) {
// create a new engine
engine := gin.New()
// create consul config
consulConfig := &api.Config{
Datacenter: config.consulDatacenter,
Address: config.consulHTTPAddr,
Token: config.consulACLToken,
Scheme: config.consulScheme,
}
// create consul client
// Set CONSUL_HTTP_ADDR in the environment that would automatically be used by the client
client, err := api.NewClient(consulConfig)
if err != nil {
return nil, errors.Wrap(err, "initializing consul client")
}
var queryOpts *api.QueryOptions
if config.consulAllowStale {
queryOpts = &api.QueryOptions{AllowStale: true}
}
return &Server{
port: config.port,
version: version,
engine: engine,
consul: &Consul{client: client, queryOpts: queryOpts},
}, nil
}
func (s *Server) Start() error {
s.engine.Use(gin.Recovery(), gin.Logger())
s.engine.GET("/", s.index)
s.engine.GET("/v1/registration/:service_name", s.registration)
log.Printf("envoy-consul-sds started - listening on port %v", s.port)
if err := s.engine.Run(fmt.Sprintf(":%v", s.port)); err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
}
func (s *Server) registration(c *gin.Context) {
// get service name from url param
serviceName := c.Param("service_name")
service, err := getService(s.consul, serviceName)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, service)
return
}
c.JSON(http.StatusOK, service)
}
func (s *Server) index(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"name": "envoy-consul-sds", "version": s.version})
}