-
Notifications
You must be signed in to change notification settings - Fork 2
/
template.go
198 lines (184 loc) · 4.5 KB
/
template.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main
import (
"bytes"
"strings"
"text/template"
)
var routerTemplate = `
import (
"net/http"
"os"
"github.com/go-woo/protoc-gen-echo/runtime"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
{{$svrType := .ServiceType}}
{{$svrName := .ServiceName}}
{{$hasJwt := .HasJwt}}
func Register{{.ServiceType}}Router(e *echo.Echo) {
{{- if $hasJwt}}
jwtKey := "dangerous"
if os.Getenv("JWTKEY") != "" {
jwtKey = os.Getenv("JWTKEY")
}
config := middleware.JWTConfig{
Claims: &JwtCustomClaims{},
SigningKey: []byte(jwtKey),
}
{{end}}
{{- range .JwtRootPaths}}
{{.RootPath}} := e.Group("/{{.RootPath}}")
{{.RootPath}}.Use(middleware.JWTWithConfig(config))
{{end}}
{{- range .Methods}}
{{- if .InScope}}
{{.Scope}}.{{.Method}}("{{.Path}}", _{{$svrType}}_{{.Name}}{{.Num}}_HTTP_Handler)
{{- else}}
e.{{.Method}}("{{.Path}}", _{{$svrType}}_{{.Name}}{{.Num}}_HTTP_Handler)
{{end}}
{{- end}}
}
{{range .Methods}}
func _{{$svrType}}_{{.Name}}{{.Num}}_HTTP_Handler(c echo.Context) error {
var req *{{.Request}} = new({{.Request}})
{{- if .HasBody}}
if err := c.Bind(req); err != nil {
return err
}
{{- end}}
uv := c.QueryParams()
{{- range .Fields}}
uv.Add("{{.ProtoName}}", c.Param("{{.ProtoName}}"))
{{- end}}
return runtime.BindValues(req, uv)
reply, err := {{$svrType}}{{.Name}}BusinessHandler(req, c)
if err != nil {
return err
}
return c.JSON(http.StatusOK, &reply)
}
{{end}}
`
var handlerTemplate = `
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/go-woo/protoc-gen-echo/runtime"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
)
{{$svrType := .ServiceType}}
{{$svrName := .ServiceName}}
{{$hasJwt := .HasJwt}}
{{range .Methods}}
func {{$svrType}}{{.Name}}BusinessHandler(req *{{.Request}}, c echo.Context) ({{.Reply}}, error) {
{{- if .IsLogin}}
// Throws unauthorized error
if req.Username != "hello" || req.Password != "world" {
return {{.Reply}}{}, echo.ErrUnauthorized
}
// Set custom claims
claims := &JwtCustomClaims{
Name: "Hello World",
Admin: true,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
},
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
jk := "dangerous"
if os.Getenv("JWTKEY") != "" {
jk = os.Getenv("JWTKEY")
}
t, err := token.SignedString([]byte(jk))
if err != nil {
return {{.Reply}}{}, err
}
{{end}}
{{- if .InScope}}
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*JwtCustomClaims)
username := claims.Name
fmt.Printf("Got jwt name is: %v\n", username)
req.Username = username
{{end}}
// Here can put your business logic, can use ORM:github.com/go-woo/protoc-gen-ent
// Below is example business logic code
rj, err := json.Marshal(req)
if err != nil {
return {{.Reply}}{}, err
}
fmt.Printf("Got {{.Request}} is: %v\n", string(rj))
{{- if .IsLogin}}
return {{.Reply}}{Token: "Bearer " + t}, nil
{{- else}}
return {{.Reply}}{}, nil {{end}}
}
{{end}}
`
var authTypeTemplate = `
import "github.com/golang-jwt/jwt"
// jwtCustomClaims are custom claims extending default ones.
// See https://github.com/golang-jwt/jwt for more examples
type JwtCustomClaims struct {
Name string ` + "`json:\"name\"`" + `
Admin bool ` + "`json:\"admin\"`" + `
jwt.StandardClaims
}
`
type serviceDesc struct {
ServiceType string // Greeter
ServiceName string // example.Greeter
Metadata string // example/v1/greeter.proto
Methods []*methodDesc
MethodSets map[string]*methodDesc
LoginUrl string
HasJwt bool
JwtRootPaths []*JwtRootPath
}
type JwtRootPath struct {
RootPath string
}
type methodDesc struct {
Name string
OriginalName string // The parsed original name
Num int
Request string
Reply string
Path string
Method string
HasVars bool
HasBody bool
Body string
ResponseBody string
Fields []*RequestField
DefaultHost string
InScope bool
Scope string
IsLogin bool
}
type RequestField struct {
ProtoName string
GoName string
GoType string
ConvExpr string
}
func (s *serviceDesc) execute(tpl string) string {
s.MethodSets = make(map[string]*methodDesc)
for _, m := range s.Methods {
s.MethodSets[m.Name] = m
}
buf := new(bytes.Buffer)
tmpl, err := template.New("http").Parse(strings.TrimSpace(tpl))
if err != nil {
panic(err)
}
if err := tmpl.Execute(buf, s); err != nil {
panic(err)
}
return strings.Trim(buf.String(), "\r\n")
}