main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "go/format"
  7. "os"
  8. "strings"
  9. "text/template"
  10. "gitea.ckfah.com/go-script/logger"
  11. "gitea.ckfah.com/go-script/utils"
  12. )
  13. type ExType string
  14. const (
  15. ServiceType = ExType("service.go")
  16. ThirdType = ExType("third.go")
  17. )
  18. type Controller struct {
  19. RouterName string
  20. URouterName string
  21. Service string
  22. UserGin bool
  23. Comment string
  24. ExType ExType
  25. }
  26. //
  27. func (c Controller) ExceptionType() string {
  28. return string(c.ExType)
  29. }
  30. //
  31. func (c Controller) GetServiceFile() string {
  32. return utils.UnMarshal(fmt.Sprintf("%sService.go", c.Service))
  33. }
  34. func (c Controller) GetControllerFile() string {
  35. return utils.UnMarshal(fmt.Sprintf("%sController.go", c.Service))
  36. }
  37. func (c Controller) GetDtoFile() string {
  38. return utils.UnMarshal(fmt.Sprintf("%sDto.go", c.Service))
  39. }
  40. // third
  41. func (c Controller) GetThirdName() string {
  42. return utils.UnMarshal(fmt.Sprintf("%sThird.go", c.Service))
  43. }
  44. func (c Controller) ThirdName() string {
  45. return fmt.Sprintf("%sThird", c.Service)
  46. }
  47. func (c Controller) ThirdServiceApolloName() string {
  48. return strings.ReplaceAll(utils.UnMarshal(c.Service), "_", "-")
  49. }
  50. // 处理 !
  51. func NewController(router string, serviceName string) Controller {
  52. // 空
  53. if router == "" || serviceName == "" {
  54. logger.FatalFH("router_name 和 service_name 不能为空!!!", printHelp)
  55. }
  56. // 非法字符 !
  57. if serviceName[0] >= '0' && serviceName[0] <= '9' {
  58. logger.FatalFH("-s=? 不能首字母是数字", printHelp)
  59. }
  60. if router[0] >= '0' && router[0] <= '9' {
  61. logger.FatalFH("-t=? 不能首字母是数字", printHelp)
  62. }
  63. // 保存最原始的r
  64. oldRouter := router
  65. router = strings.TrimPrefix(router, "/")
  66. router = strings.TrimSuffix(router, "/")
  67. // add /
  68. oldRouter = "/" + router
  69. // r 去除service_name
  70. //if strings.HasPrefix(router, serviceName) {
  71. // router = strings.TrimPrefix(router, serviceName)
  72. //}
  73. // service-name 转换为 驼峰
  74. serviceName = utils.Marshal(strings.ReplaceAll(serviceName, "-", "_"))
  75. if strings.HasSuffix(serviceName, "Service") {
  76. serviceName = strings.TrimSuffix(serviceName, "Service")
  77. }
  78. if strings.HasSuffix(serviceName, "Controller") {
  79. serviceName = strings.TrimSuffix(serviceName, "Controller")
  80. }
  81. if strings.HasSuffix(serviceName, "Third") {
  82. serviceName = strings.TrimSuffix(serviceName, "Third")
  83. }
  84. // 转换为下划线 !!!
  85. if strings.Contains(router, "/") {
  86. split := strings.Split(router, "/")
  87. router = strings.Join(split, "_")
  88. }
  89. router = strings.ReplaceAll(router, "-", "_")
  90. // 初始化!!!!
  91. return Controller{
  92. RouterName: utils.Marshal(router),
  93. URouterName: oldRouter,
  94. Service: serviceName,
  95. }
  96. }
  97. func (c Controller) ContextName() string {
  98. if userGin {
  99. return "*gin.Context"
  100. }
  101. return "*engines.Context"
  102. }
  103. func (c Controller) Common() string {
  104. if c.Comment == "" {
  105. return ""
  106. }
  107. return fmt.Sprintf("// %s", c.Comment)
  108. }
  109. func (c Controller) GetPath() string {
  110. return c.URouterName
  111. }
  112. func (c Controller) ControllerName() string {
  113. if c.Service == "" {
  114. logger.FatalF("-s 不能为空!!!!,否则无法生成模版")
  115. }
  116. return fmt.Sprintf("%s%s", LowerName(c.Service), "Controller")
  117. }
  118. func (c Controller) FuncName() string {
  119. return UpperName(c.RouterName)
  120. }
  121. func (c Controller) RequestName() string {
  122. return fmt.Sprintf("%s%s", UpperName(c.RouterName), "Request")
  123. }
  124. func (c Controller) ServiceName() string {
  125. if c.Service == "" {
  126. logger.FatalF("-s 不能为空!!!!,否则无法生成模版")
  127. }
  128. return fmt.Sprintf("%s%s", LowerName(c.Service), "Service")
  129. }
  130. func (c Controller) Params() string {
  131. return "params"
  132. }
  133. func LowerName(str string) string {
  134. if str[0] >= 'A' && str[0] <= 'Z' {
  135. newStr := []byte(str)
  136. newStr[0] = newStr[0] + 32
  137. return string(newStr)
  138. }
  139. return str
  140. }
  141. func UpperName(str string) string {
  142. if str[0] >= 'a' && str[0] <= 'z' {
  143. newStr := []byte(str)
  144. newStr[0] = newStr[0] - 32
  145. return string(newStr)
  146. }
  147. return str
  148. }
  149. func NewJsonTag(str string) string {
  150. return fmt.Sprintf("`json:\"%s\" binding:\"required\"`", str)
  151. }
  152. var newT = `
  153. // ======================={{.GetControllerFile}}==============================
  154. type {{LowerName .ControllerName}} struct {
  155. }
  156. func New{{UpperName .ControllerName}}() *{{LowerName .ControllerName}} {
  157. return new({{LowerName .ControllerName}})
  158. }
  159. var (
  160. {{LowerName .ServiceName}} = service.New{{UpperName .ServiceName}}()
  161. )
  162. // ======================={{.GetServiceFile}}==============================
  163. type {{LowerName .ServiceName}} struct {
  164. }
  165. func New{{UpperName .ServiceName}}() *{{LowerName .ServiceName}} {
  166. return new({{LowerName .ServiceName}})
  167. }
  168. `
  169. var (
  170. controllerT = `
  171. // ======================={{.GetControllerFile}}==============================
  172. {{.Common}}
  173. func(this *{{.ControllerName}}){{.FuncName}}(ctx {{.ContextName}}){
  174. request := new(vo.{{.RequestName}})
  175. err := ctx.BindJSON(request)
  176. if err != nil {
  177. logger.Warnc(ctx, "[{{.FuncName}}] bind params err,err=%v", err)
  178. common.FailJson(ctx, exception.ParamsBindError)
  179. return
  180. }
  181. logger.Infoc(ctx, "[{{.FuncName}}] start,request=%+v", request)
  182. result, cerr := {{.ServiceName}}.{{.FuncName}}(ctx, &request.Params)
  183. if cerr != nil {
  184. logger.Warnc(ctx, "[{{.FuncName}}] end err,err=%v", cerr)
  185. common.FailJson(ctx, cerr)
  186. return
  187. }
  188. logger.Infoc(ctx, "[{{.FuncName}}] end,result=%+v", result)
  189. common.SuccessJson(ctx, result)
  190. }`
  191. )
  192. var (
  193. dtoT = `
  194. // ======================={{.GetDtoFile}}==============================
  195. {{.Common}}
  196. type {{UpperName .FuncName}}Request struct {
  197. Params dto.{{UpperName .FuncName}}Params {{NewJsonTag .Params}}
  198. }
  199. type {{UpperName .FuncName}}Params struct {
  200. }
  201. type {{UpperName .FuncName}}Result struct {
  202. }
  203. `
  204. )
  205. var (
  206. serviceT = `
  207. // ======================={{.GetServiceFile}}==============================
  208. {{.Common}}
  209. func (this *{{LowerName .ServiceName}}) {{UpperName .FuncName}}(context {{.ContextName}}, params *dto.{{UpperName .FuncName}}Params) (*dto.{{UpperName .FuncName}}Result, cerror.Cerror) {
  210. return nil, nil
  211. }
  212. `
  213. )
  214. var (
  215. thirdT = `
  216. // ==========================={{.GetThirdName}}===========================
  217. // api-doc-address:
  218. type {{LowerName .ThirdName}} struct {
  219. }
  220. func New{{UpperName .ThirdName}}() *{{LowerName .ThirdName}} {
  221. return &{{LowerName .ThirdName}}{}
  222. }
  223. const (
  224. _{{UpperName .ThirdName}}ServerName = "{{.ThirdServiceApolloName}}"
  225. )
  226. func (*{{LowerName .ThirdName}}) GetServerName() string {
  227. return _{{UpperName .ThirdName}}ServerName
  228. }
  229. {{.Common}}
  230. func (this *{{LowerName .ThirdName}}) {{UpperName .FuncName}}(ctx {{.ContextName}},params *dto.{{UpperName .FuncName}}Params) (*dto.{{UpperName .FuncName}}Response, cerror.Cerror) {
  231. path := "{{.GetPath}}"
  232. response := new(dto.{{UpperName .FuncName}}Response)
  233. err := util.HttpRequestAndDecode(ctx, this.GetServerName(), path, params, response)
  234. if err != nil {
  235. logger.Warnc(ctx, "[{{UpperName .FuncName}}] request err,params=%+v,err=%v", params, err)
  236. return nil, exception.{{UpperName .FuncName}}Error(err)
  237. }
  238. return response, nil
  239. }
  240. `
  241. )
  242. var (
  243. thirdDtoT = `
  244. // ======================={{.GetDtoFile}}==============================
  245. {{.Common}}
  246. type {{UpperName .FuncName}}Params struct {
  247. }
  248. type {{UpperName .FuncName}}Response struct {
  249. }
  250. `
  251. )
  252. var (
  253. apolloConfigT = `
  254. //======================= config/apollo/namespaces.json =======================
  255. {
  256. "name": "{{.ThirdServiceApolloName}}",
  257. "keys": [
  258. {
  259. "name": "{{.ThirdServiceApolloName}}.host",
  260. "mapTo": "host"
  261. },
  262. {
  263. "name": "{{.ThirdServiceApolloName}}.key",
  264. "mapTo": "key"
  265. },
  266. {
  267. "name": "{{.ThirdServiceApolloName}}.name",
  268. "mapTo": "name"
  269. }
  270. ]
  271. }
  272. //======================= apollo添加properties,注意host key=======================
  273. # {{.ThirdServiceApolloName}} 服务
  274. {{.ThirdServiceApolloName}}.host=
  275. {{.ThirdServiceApolloName}}.key=
  276. {{.ThirdServiceApolloName}}.name={{.ThirdServiceApolloName}}
  277. //=======================如果不是apollo,请在env.ini中添加,注意host key=======================
  278. ;{{.ThirdServiceApolloName}} 服务
  279. [{{.ThirdServiceApolloName}}]
  280. host=
  281. key=
  282. name={{.ThirdServiceApolloName}}
  283. `
  284. )
  285. var (
  286. exceptionServiceT = `
  287. // ======================{{.ExceptionType}}==================================
  288. {{UpperName .FuncName}}Error = util.NewSCerror({{LowerName .FuncName}}ErrorCode)
  289. `
  290. )
  291. var (
  292. exceptionThirdT = `
  293. // ======================{{.ExceptionType}}==================================
  294. {{UpperName .FuncName}}Error = util.NewECerror({{LowerName .FuncName}}ErrorCode)
  295. `
  296. )
  297. var (
  298. common string
  299. url string
  300. service string
  301. gThird bool // 生成third
  302. helps bool
  303. onlyDto bool
  304. onlyMew bool
  305. onlyService bool
  306. onlyController bool
  307. userGin bool
  308. )
  309. func main() {
  310. flag.StringVar(&url, "r", "", "请求路由,比如/echo,生成Echo方法,/user/list生成UserList,必须传递")
  311. flag.StringVar(&service, "s", "", "生成的Service/Controller名字,比如 user,则生成userService,必须传递")
  312. flag.BoolVar(&helps, "h", false, "帮助!!")
  313. flag.BoolVar(&gThird, "t", false, "生成third,注意也是复用router 和 service_name,所以必须传递-r -s!!")
  314. flag.BoolVar(&onlyDto, "od", false, "比如 -od 只生成Dto对象")
  315. flag.BoolVar(&onlyMew, "on", false, "只生成New方法")
  316. flag.BoolVar(&onlyService, "os", false, "只生成Service方法")
  317. flag.BoolVar(&onlyController, "oc", false, "只生成Controller方法")
  318. flag.BoolVar(&userGin, "ug", false, "使用gin框架,默认是gauss")
  319. flag.StringVar(&common, "c", "", "方法注释!!service方法和controller方法注释是一样的奥!!不传不生成")
  320. Init()
  321. t := template.New("")
  322. t = t.Funcs(template.FuncMap{
  323. "LowerName": LowerName,
  324. "UpperName": UpperName,
  325. "NewJsonTag": NewJsonTag,
  326. "UtilUnMarshal": utils.UnMarshal,
  327. })
  328. controller := NewController(url, service)
  329. controller.UserGin = userGin
  330. controller.Comment = common
  331. fmt.Printf("==================touch file=======================\n")
  332. if gThird {
  333. controller.ExType = ThirdType
  334. fmt.Printf("third: %s\ndto: %s\n注意配置 apollo or env\n",
  335. controller.GetThirdName(),
  336. controller.GetDtoFile(),
  337. )
  338. exec(t, thirdT, controller)
  339. exec(t, thirdDtoT, controller)
  340. execNotFormat(t, apolloConfigT, controller)
  341. execNotFormat(t, exceptionThirdT, controller)
  342. os.Exit(-1)
  343. }
  344. controller.ExType = ServiceType
  345. fmt.Printf("controller: %s\nservice: %s\ndto: %s\n\n",
  346. controller.GetControllerFile(),
  347. controller.GetServiceFile(),
  348. controller.GetDtoFile(),
  349. )
  350. if onlyMew {
  351. exec(t, newT, controller)
  352. os.Exit(-1)
  353. }
  354. if onlyController {
  355. exec(t, controllerT, controller)
  356. os.Exit(-1)
  357. }
  358. if onlyDto {
  359. exec(t, dtoT, controller)
  360. os.Exit(-1)
  361. }
  362. if onlyService {
  363. exec(t, serviceT, controller)
  364. execNotFormat(t, exceptionServiceT, controller)
  365. os.Exit(-1)
  366. }
  367. exec(t, newT, controller)
  368. exec(t, controllerT, controller)
  369. exec(t, dtoT, controller)
  370. exec(t, serviceT, controller)
  371. execNotFormat(t, exceptionServiceT, controller)
  372. os.Exit(-1)
  373. }
  374. func exec(t *template.Template, str string, data interface{}) {
  375. parse, err := t.Parse(str)
  376. if err != nil {
  377. panic(err)
  378. }
  379. buffer := &bytes.Buffer{}
  380. err = parse.Execute(buffer, data)
  381. if err != nil {
  382. panic(err)
  383. }
  384. source, err := format.Source(buffer.Bytes())
  385. if err != nil {
  386. panic(err)
  387. }
  388. fmt.Printf("%s\n", source)
  389. }
  390. func execNotFormat(t *template.Template, str string, data interface{}) {
  391. parse, err := t.Parse(str)
  392. if err != nil {
  393. panic(err)
  394. }
  395. buffer := &bytes.Buffer{}
  396. err = parse.Execute(buffer, data)
  397. if err != nil {
  398. panic(err)
  399. }
  400. fmt.Printf("%s\n", buffer.Bytes())
  401. }
  402. func Init() {
  403. flag.Parse()
  404. if helps {
  405. printHelp()
  406. os.Exit(-1)
  407. }
  408. }
  409. func printHelp() {
  410. fmt.Println(`================go-new help=====================
  411. go-new -r=/user/list -s=user
  412. Option:`)
  413. flag.PrintDefaults()
  414. }