-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
84 lines (69 loc) · 1.7 KB
/
service.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
package service
import (
"context"
"fmt"
"net"
"net/http"
"strings"
proto "github.com/derarken/vlr-api/gen/vlr/api"
"github.com/flowchartsman/swaggerui"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/reflection"
)
const (
grpcPort = ":8080"
gatewayPort = ":8090"
)
type Server struct {
proto.UnimplementedApiServer
}
func NewServer() *Server {
return &Server{}
}
func Start(swaggerJSON []byte) {
listener, err := net.Listen("tcp", grpcPort)
if err != nil {
panic(err)
}
s := grpc.NewServer()
apiServer := NewServer()
proto.RegisterApiServer(s, apiServer)
reflection.Register(s)
grpclog.Infof("gRPC service %s running on %s", proto.Api_ServiceDesc.ServiceName, grpcPort)
go func() {
err = s.Serve(listener)
if err != nil {
panic(err)
}
}()
startGateway(swaggerJSON)
}
func startGateway(swaggerJSON []byte) {
conn, err := grpc.NewClient(fmt.Sprintf("dns:///%s", grpcPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
panic(err)
}
gatewayMux := runtime.NewServeMux()
err = proto.RegisterApiHandler(context.Background(), gatewayMux, conn)
if err != nil {
panic(err)
}
server := &http.Server{
Addr: gatewayPort,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/v1") {
gatewayMux.ServeHTTP(w, r)
return
}
swaggerui.Handler(swaggerJSON).ServeHTTP(w, r)
}),
}
grpclog.Infof("gRPC gateway %s and SwaggerUI running on %s", proto.Api_ServiceDesc.ServiceName, gatewayPort)
err = server.ListenAndServe()
if err != nil {
panic(err)
}
}