forked from grpc-ecosystem/protoc-gen-grpc-gateway-ts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
99 lines (84 loc) · 1.96 KB
/
main.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
95
96
97
98
99
package main
import (
"io/ioutil"
"os"
"strings"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
log "github.com/sirupsen/logrus" // nolint: depguard
"google.golang.org/protobuf/proto"
"github.com/grpc-ecosystem/protoc-gen-grpc-gateway-ts/generator"
"github.com/pkg/errors"
)
func decodeReq() *plugin.CodeGeneratorRequest {
req := &plugin.CodeGeneratorRequest{}
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
err = proto.Unmarshal(data, req)
if err != nil {
panic(err)
}
return req
}
func encodeResponse(resp proto.Message) {
data, err := proto.Marshal(resp)
if err != nil {
panic(err)
}
_, err = os.Stdout.Write(data)
if err != nil {
panic(err)
}
}
func main() {
req := decodeReq()
paramsMap := getParamsMap(req)
err := configureLogging(paramsMap)
if err != nil {
panic(err)
}
g, err := generator.New(paramsMap)
if err != nil {
panic(err)
}
log.Debug("Starts generating file request")
resp, err := g.Generate(req)
if err != nil {
panic(err)
}
encodeResponse(resp)
log.Debug("generation finished")
}
func configureLogging(paramsMap map[string]string) error {
if paramsMap["logtostderr"] == "true" { // configure logging when it's in the options
log.SetFormatter(&log.TextFormatter{
DisableTimestamp: true,
})
log.SetOutput(os.Stderr)
log.Debugf("Logging configured completed, logging has been enabled")
levelStr := paramsMap["loglevel"]
if levelStr != "" {
level, err := log.ParseLevel(levelStr)
if err != nil {
return errors.Wrapf(err, "error parsing log level %s", levelStr)
}
log.SetLevel(level)
} else {
log.SetLevel(log.InfoLevel)
}
}
return nil
}
func getParamsMap(req *plugin.CodeGeneratorRequest) map[string]string {
paramsMap := make(map[string]string)
params := req.GetParameter()
for _, p := range strings.Split(params, ",") {
if i := strings.Index(p, "="); i < 0 {
paramsMap[p] = ""
} else {
paramsMap[p[0:i]] = p[i+1:]
}
}
return paramsMap
}