1 Star 0 Fork 0

kevin2027 / protoc-gen-go-gin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
template.go 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
mohuishou 提交于 2021-02-25 13:47 . feat: 完善示例
package main
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"strings"
)
//go:embed template.go.tpl
var tpl string
type service struct {
Name string // Greeter
FullName string // helloworld.Greeter
FilePath string // api/helloworld/helloworld.proto
Methods []*method
MethodSet map[string]*method
}
func (s *service) execute() string {
if s.MethodSet == nil {
s.MethodSet = map[string]*method{}
for _, m := range s.Methods {
m := m
s.MethodSet[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 buf.String()
}
// InterfaceName service interface name
func (s *service) InterfaceName() string {
return s.Name + "HTTPServer"
}
type method struct {
Name string // SayHello
Num int // 一个 rpc 方法可以对应多个 http 请求
Request string // SayHelloReq
Reply string // SayHelloResp
// http_rule
Path string // 路由
Method string // HTTP Method
Body string
ResponseBody string
}
// HandlerName for gin handler name
func (m *method) HandlerName() string {
return fmt.Sprintf("%s_%d", m.Name, m.Num)
}
// HasPathParams 是否包含路由参数
func (m *method) HasPathParams() bool {
paths := strings.Split(m.Path, "/")
for _, p := range paths {
if len(p) > 0 && (p[0] == '{' && p[len(p)-1] == '}' || p[0] == ':') {
return true
}
}
return false
}
// initPathParams 转换参数路由 {xx} --> :xx
func (m *method) initPathParams() {
paths := strings.Split(m.Path, "/")
for i, p := range paths {
if len(p) > 0 && (p[0] == '{' && p[len(p)-1] == '}' || p[0] == ':') {
paths[i] = ":" + p[1:len(p)-1]
}
}
m.Path = strings.Join(paths, "/")
}
Go
1
https://gitee.com/kevin2027/protoc-gen-go-gin.git
git@gitee.com:kevin2027/protoc-gen-go-gin.git
kevin2027
protoc-gen-go-gin
protoc-gen-go-gin
v0.1.3

搜索帮助