template.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package main
  2. const (
  3. _tplAppToml = `
  4. # This is a TOML document. Boom
  5. `
  6. _tplMySQLToml = `
  7. [demo]
  8. addr = "127.0.0.1:3306"
  9. dsn = "{user}:{password}@tcp(127.0.0.1:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8mb4,utf8"
  10. readDSN = ["{user}:{password}@tcp(127.0.0.2:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8mb4,utf8","{user}:{password}@tcp(127.0.0.3:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"]
  11. active = 20
  12. idle = 10
  13. idleTimeout ="4h"
  14. queryTimeout = "200ms"
  15. execTimeout = "300ms"
  16. tranTimeout = "400ms"
  17. `
  18. _tplMCToml = `
  19. demoExpire = "24h"
  20. [demo]
  21. name = "{{.Name}}"
  22. proto = "tcp"
  23. addr = "127.0.0.1:11211"
  24. active = 50
  25. idle = 10
  26. dialTimeout = "100ms"
  27. readTimeout = "200ms"
  28. writeTimeout = "300ms"
  29. idleTimeout = "80s"
  30. `
  31. _tplRedisToml = `
  32. demoExpire = "24h"
  33. [demo]
  34. name = "{{.Name}}"
  35. proto = "tcp"
  36. addr = "127.0.0.1:6389"
  37. idle = 10
  38. active = 10
  39. dialTimeout = "1s"
  40. readTimeout = "1s"
  41. writeTimeout = "1s"
  42. idleTimeout = "10s"
  43. `
  44. _tplHTTPToml = `
  45. [server]
  46. addr = "0.0.0.0:8000"
  47. timeout = "1s"
  48. `
  49. _tplGRPCToml = `
  50. [server]
  51. addr = "0.0.0.0:9000"
  52. timeout = "1s"
  53. `
  54. _tplChangeLog = `### v1.0.0
  55. 1. 上线功能xxx
  56. `
  57. _tplMain = `package main
  58. import (
  59. "context"
  60. "flag"
  61. "os"
  62. "os/signal"
  63. "syscall"
  64. "time"
  65. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/server/grpc"
  66. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/server/http"
  67. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/service"
  68. "go-common/library/conf/paladin"
  69. ecode "go-common/library/ecode/tip"
  70. "go-common/library/log"
  71. )
  72. func main() {
  73. flag.Parse()
  74. if err := paladin.Init(); err != nil {
  75. panic(err)
  76. }
  77. log.Init(nil) // debug flag: log.dir={path}
  78. defer log.Close()
  79. log.Info("{{.Name}}-{{.Type}} start")
  80. ecode.Init(nil)
  81. svc := service.New()
  82. grpcSrv := grpc.New(svc)
  83. httpSrv := http.New(svc)
  84. c := make(chan os.Signal, 1)
  85. signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
  86. for {
  87. s := <-c
  88. log.Info("get a signal %s", s.String())
  89. switch s {
  90. case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
  91. ctx, _ := context.WithTimeout(context.Background(), 35*time.Second)
  92. grpcSrv.Shutdown(ctx)
  93. httpSrv.Shutdown(ctx)
  94. log.Info("{{.Name}}-{{.Type}} exit")
  95. svc.Close()
  96. time.Sleep(time.Second)
  97. return
  98. case syscall.SIGHUP:
  99. default:
  100. return
  101. }
  102. }
  103. }
  104. `
  105. _tplContributors = `# Owner
  106. {{.Owner}}
  107. # Author
  108. # Reviewer
  109. `
  110. _tplDao = `package dao
  111. import (
  112. "context"
  113. "time"
  114. "go-common/library/cache/memcache"
  115. "go-common/library/cache/redis"
  116. "go-common/library/conf/paladin"
  117. "go-common/library/database/sql"
  118. "go-common/library/log"
  119. xtime "go-common/library/time"
  120. )
  121. // Dao dao.
  122. type Dao struct {
  123. db *sql.DB
  124. redis *redis.Pool
  125. redisExpire int32
  126. mc *memcache.Pool
  127. mcExpire int32
  128. }
  129. func checkErr(err error) {
  130. if err != nil {
  131. panic(err)
  132. }
  133. }
  134. // New new a dao and return.
  135. func New() (dao *Dao) {
  136. var (
  137. dc struct {
  138. Demo *sql.Config
  139. }
  140. rc struct {
  141. Demo *redis.Config
  142. DemoExpire xtime.Duration
  143. }
  144. mc struct {
  145. Demo *memcache.Config
  146. DemoExpire xtime.Duration
  147. }
  148. )
  149. checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
  150. checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
  151. checkErr(paladin.Get("memcache.toml").UnmarshalTOML(&mc))
  152. dao = &Dao{
  153. // mysql
  154. db: sql.NewMySQL(dc.Demo),
  155. // redis
  156. redis: redis.NewPool(rc.Demo),
  157. redisExpire: int32(time.Duration(rc.DemoExpire) / time.Second),
  158. // memcache
  159. mc: memcache.NewPool(mc.Demo),
  160. mcExpire: int32(time.Duration(mc.DemoExpire) / time.Second),
  161. }
  162. return
  163. }
  164. // Close close the resource.
  165. func (d *Dao) Close() {
  166. d.mc.Close()
  167. d.redis.Close()
  168. d.db.Close()
  169. }
  170. // Ping ping the resource.
  171. func (d *Dao) Ping(ctx context.Context) (err error) {
  172. if err = d.pingMC(ctx); err != nil {
  173. return
  174. }
  175. if err = d.pingRedis(ctx); err != nil {
  176. return
  177. }
  178. return d.db.Ping(ctx)
  179. }
  180. func (d *Dao) pingMC(ctx context.Context) (err error) {
  181. conn := d.mc.Get(ctx)
  182. defer conn.Close()
  183. if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
  184. log.Error("conn.Set(PING) error(%v)", err)
  185. }
  186. return
  187. }
  188. func (d *Dao) pingRedis(ctx context.Context) (err error) {
  189. conn := d.redis.Get(ctx)
  190. defer conn.Close()
  191. if _, err = conn.Do("SET", "ping", "pong"); err != nil {
  192. log.Error("conn.Set(PING) error(%v)", err)
  193. }
  194. return
  195. }
  196. `
  197. _tplReadme = `# {{.Name}}-{{.Type}}
  198. ## 项目简介
  199. 1.
  200. ## 编译环境
  201. ## 依赖包
  202. ## 编译执行
  203. `
  204. _tplService = `package service
  205. import (
  206. "context"
  207. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/dao"
  208. "go-common/library/conf/paladin"
  209. )
  210. // Service service.
  211. type Service struct {
  212. ac *paladin.Map
  213. dao *dao.Dao
  214. }
  215. // New new a service and return.
  216. func New() (s *Service) {
  217. var ac = new(paladin.TOML)
  218. if err := paladin.Watch("application.toml", ac); err != nil {
  219. panic(err)
  220. }
  221. s = &Service{
  222. ac: ac,
  223. dao: dao.New(),
  224. }
  225. return s
  226. }
  227. // Ping ping the resource.
  228. func (s *Service) Ping(ctx context.Context) (err error) {
  229. return s.dao.Ping(ctx)
  230. }
  231. // Close close the resource.
  232. func (s *Service) Close() {
  233. s.dao.Close()
  234. }
  235. `
  236. _tplGPRCService = `package service
  237. import (
  238. "context"
  239. "fmt"
  240. pb "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/api"
  241. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/dao"
  242. "go-common/library/conf/paladin"
  243. "github.com/golang/protobuf/ptypes/empty"
  244. )
  245. // Service service.
  246. type Service struct {
  247. ac *paladin.Map
  248. dao *dao.Dao
  249. }
  250. // New new a service and return.
  251. func New() (s *Service) {
  252. var ac = new(paladin.TOML)
  253. if err := paladin.Watch("application.toml", ac); err != nil {
  254. panic(err)
  255. }
  256. s = &Service{
  257. ac: ac,
  258. dao: dao.New(),
  259. }
  260. return s
  261. }
  262. // SayHello grpc demo func.
  263. func (s *Service) SayHello(ctx context.Context, req *pb.HelloReq) (reply *empty.Empty, err error) {
  264. reply = new(empty.Empty)
  265. fmt.Printf("hello %s", req.Name)
  266. return
  267. }
  268. // Ping ping the resource.
  269. func (s *Service) Ping(ctx context.Context) (err error) {
  270. return s.dao.Ping(ctx)
  271. }
  272. // Close close the resource.
  273. func (s *Service) Close() {
  274. s.dao.Close()
  275. }
  276. `
  277. _tplHTTPServer = `package http
  278. import (
  279. "net/http"
  280. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/service"
  281. "go-common/library/conf/paladin"
  282. "go-common/library/log"
  283. bm "go-common/library/net/http/blademaster"
  284. "go-common/library/net/http/blademaster/middleware/verify"
  285. )
  286. var (
  287. svc *service.Service
  288. )
  289. // New new a bm server.
  290. func New(s *service.Service) (engine *bm.Engine) {
  291. var(
  292. hc struct {
  293. Server *bm.ServerConfig
  294. }
  295. )
  296. if err := paladin.Get("http.toml").UnmarshalTOML(&hc); err != nil {
  297. if err != paladin.ErrNotExist {
  298. panic(err)
  299. }
  300. }
  301. svc = s
  302. engine = bm.DefaultServer(hc.Server)
  303. initRouter(engine, verify.New(nil))
  304. if err := engine.Start(); err != nil {
  305. panic(err)
  306. }
  307. return
  308. }
  309. func initRouter(e *bm.Engine, v *verify.Verify) {
  310. e.Ping(ping)
  311. e.Register(register)
  312. g := e.Group("/x/{{.Name}}")
  313. {
  314. g.GET("/start", v.Verify, howToStart)
  315. }
  316. }
  317. func ping(ctx *bm.Context) {
  318. if err := svc.Ping(ctx); err != nil {
  319. log.Error("ping error(%v)", err)
  320. ctx.AbortWithStatus(http.StatusServiceUnavailable)
  321. }
  322. }
  323. func register(c *bm.Context) {
  324. c.JSON(map[string]interface{}{}, nil)
  325. }
  326. // example for http request handler.
  327. func howToStart(c *bm.Context) {
  328. c.String(0, "Golang 大法好 !!!")
  329. }
  330. `
  331. _tplAPIProto = `// 定义项目 API 的 proto 文件 可以同时描述 gRPC 和 HTTP API
  332. // protobuf 文件参考:
  333. // - https://developers.google.com/protocol-buffers/
  334. // - http://info.bilibili.co/display/documentation/gRPC+Proto
  335. // protobuf 生成 HTTP 工具:
  336. // - http://git.bilibili.co/platform/go-common/tree/master/app/tool/protoc-gen-bm
  337. // gRPC Golang Model:
  338. // - http://info.bilibili.co/display/documentation/gRPC+Golang+Model
  339. // gRPC Golang Warden Gen:
  340. // - http://info.bilibili.co/display/documentation/gRPC+Golang+Warden+Gen
  341. // gRPC http 调试工具(无需pb文件):
  342. // - http://info.bilibili.co/pages/viewpage.action?pageId=12877366
  343. // grpc 命令行调试工具(无需pb文件):
  344. // - http://info.bilibili.co/pages/viewpage.action?pageId=11869411
  345. syntax = "proto3";
  346. import "github.com/gogo/protobuf/gogoproto/gogo.proto";
  347. import "google/protobuf/empty.proto";
  348. // package 命名使用 {discovery_id}.{version} 的方式, version 形如 v1, v2, v1beta ..
  349. // NOTE: 不知道的 discovery_id 请询问大佬, 新项目找大佬申请 discovery_id,先到先得抢注
  350. // e.g. account.service.v1
  351. package demo.service.v1;
  352. // NOTE: 最后请删除这些无用的注释 (゜-゜)つロ
  353. option go_package = "api";
  354. // do not generate getXXX() method
  355. option (gogoproto.goproto_getters_all) = false;
  356. service Demo {
  357. rpc SayHello (HelloReq) returns (.google.protobuf.Empty);
  358. }
  359. message HelloReq {
  360. string name = 1 [(gogoproto.moretags)='form:"name" validate:"required"'];
  361. }
  362. `
  363. _tplAPIGenerate = `package api
  364. // 生成 gRPC 代码
  365. //go:generate $GOPATH/src/go-common/app/tool/warden/protoc.sh
  366. `
  367. _tplModel = `package model
  368. `
  369. _tplGRPCServer = `package grpc
  370. import (
  371. pb "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/api"
  372. "go-common/app/{{.Type}}/{{.Department}}/{{.Name}}/internal/service"
  373. "go-common/library/net/rpc/warden"
  374. "go-common/library/conf/paladin"
  375. )
  376. // New new a grpc server.
  377. func New(svc *service.Service) *warden.Server {
  378. var rc struct {
  379. Server *warden.ServerConfig
  380. }
  381. if err := paladin.Get("grpc.toml").UnmarshalTOML(&rc); err != nil {
  382. if err != paladin.ErrNotExist {
  383. panic(err)
  384. }
  385. }
  386. ws := warden.NewServer(rc.Server)
  387. pb.RegisterDemoServer(ws.Server(), svc)
  388. ws, err := ws.Start()
  389. if err != nil {
  390. panic(err)
  391. }
  392. return ws
  393. }
  394. `
  395. )