/
rest.go
90 lines (73 loc) · 2.3 KB
/
rest.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
package cmd
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"
pb "github.com/dinhtp/lets-go-pbtype/company"
)
var restCmd = &cobra.Command{
Use: "rest",
Short: "go company service serve rest command",
Run: runRestCommand,
}
func init() {
serveCmd.AddCommand(restCmd)
restCmd.Flags().StringP("backend", "", "backend", "grpc backend address")
restCmd.Flags().StringP("address", "", "address", "rest gateway address")
_ = viper.BindPFlag("address", restCmd.Flags().Lookup("address"))
_ = viper.BindPFlag("backend", restCmd.Flags().Lookup("backend"))
}
func runRestCommand(cmd *cobra.Command, args []string) {
ctx := context.Background()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
address := viper.GetString("address")
backend := viper.GetString("backend")
mux := http.NewServeMux()
GatewayMux := runtime.NewServeMux()
go func() {
opts := []grpc.DialOption{grpc.WithInsecure()}
initializeGatewayService(ctx, GatewayMux, backend, opts)
}()
mux.Handle("/", GatewayMux)
srv := &http.Server{
Addr: address,
Handler: mux,
IdleTimeout: 60 * time.Second,
ReadTimeout: 20 * time.Second,
WriteTimeout: 20 * time.Second,
}
go func() {
err := srv.ListenAndServe()
if nil != err {
panic(err)
}
}()
logrus.WithFields(logrus.Fields{
"service": "go-company-service",
"type": "rest",
}).Info("go company service server started")
<-c
ctx, cancel := context.WithCancel(ctx)
defer cancel()
logrus.WithFields(logrus.Fields{
"service": "go-company-service",
"type": "rest",
}).Info("go company service gracefully shutdowns")
}
func initializeGatewayService(ctx context.Context, gw *runtime.ServeMux, endpoint string, opts []grpc.DialOption) {
companyGwErr := pb.RegisterCompanyServiceHandlerFromEndpoint(ctx, gw, endpoint, opts)
if nil != companyGwErr {
fmt.Println(companyGwErr)
os.Exit(1)
}
}