Repository: zeromicro/go-zero
Pull request #3790 (2023-12-13 14:58:16)

feat: add gen api @doc comment to logic handler routes
example:

demo.api
```
syntax = "v1"

type Request {
	Name string `path:"name,options=you|me"`
}

type Response {
	Message string `json:"message"`
}

service demo-api {

	@doc "demo comment"
	@handler DemoHandler
	get /from/:name(Request) returns (Response)

	@doc ("demo list comment")
	@handler DemoListHandler
	get /from/list returns (Response)

	@doc(
		summary: "comment comment comment"
	)
	@handler NoResponseHandler
	get /from/get (Request)
}
```
generate  logic  handler routes comment

![image](https://github.com/zeromicro/go-zero/assets/40114564/caa7f95e-5127-4235-90eb-60061e1ffef9)

![image](https://github.com/zeromicro/go-zero/assets/40114564/7bea3b6f-6dac-4b75-8059-3065ee7a6a19)

![image](https://github.com/zeromicro/go-zero/assets/40114564/efb85987-e827-427a-bb12-931d53d99573)





ch3nnn: @kevwan I hope you can help me see if this change is reasonable and correct. thank!
ch3nnn: i see change approved, want to know the current PR can be merged ? @kevwan 
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/zeromicro/go-zero/pull/3790?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=zeromicro) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 94.53%. Comparing base [(`2629636`)](https://app.codecov.io/gh/zeromicro/go-zero/commit/2629636f648bd829f5643c63b5359292be565eac?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=zeromicro) to head [(`adeaf74`)](https://app.codecov.io/gh/zeromicro/go-zero/pull/3790?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=zeromicro).
> Report is 40 commits behind head on master.

> :exclamation: Current head adeaf74 differs from pull request most recent head ce85e1b. Consider uploading reports for the commit ce85e1b to get more accurate results

<details><summary>Additional details and impacted files</summary>



[see 7 files with indirect coverage changes](https://app.codecov.io/gh/zeromicro/go-zero/pull/3790/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=zeromicro)

</details>

Patch:
diff --git a/tools/goctl/api/gogen/genhandlers.go b/tools/goctl/api/gogen/genhandlers.go
index fa1093ec..4611be4d 100644
--- a/tools/goctl/api/gogen/genhandlers.go
+++ b/tools/goctl/api/gogen/genhandlers.go
@@ -18,19 +18,6 @@ const defaultLogicPackage = "logic"
 //go:embed handler.tpl
 var handlerTemplate string
 
-type handlerInfo struct {
-	PkgName            string
-	ImportPackages     string
-	ImportHttpxPackage string
-	HandlerName        string
-	RequestType        string
-	LogicName          string
-	LogicType          string
-	Call               string
-	HasResp            bool
-	HasRequest         bool
-}
-
 func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
 	handler := getHandlerName(route)
 	handlerPath := getHandlerFolderPath(group, route)
@@ -40,23 +27,6 @@ func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route
 		handler = strings.Title(handler)
 		logicName = pkgName
 	}
-
-	return doGenToFile(dir, handler, cfg, group, route, handlerInfo{
-		PkgName:        pkgName,
-		ImportPackages: genHandlerImports(group, route, rootPkg),
-		HandlerName:    handler,
-		RequestType:    util.Title(route.RequestTypeName()),
-		LogicName:      logicName,
-		LogicType:      strings.Title(getLogicName(route)),
-		Call:           strings.Title(strings.TrimSuffix(handler, "Handler")),
-		HasResp:        len(route.ResponseTypeName()) > 0,
-		HasRequest:     len(route.RequestTypeName()) > 0,
-	})
-}
-
-func doGenToFile(dir, handler string, cfg *config.Config, group spec.Group,
-	route spec.Route, handleObj handlerInfo,
-) error {
 	filename, err := format.FileNamingFormat(cfg.NamingFormat, handler)
 	if err != nil {
 		return err
@@ -70,7 +40,19 @@ func doGenToFile(dir, handler string, cfg *config.Config, group spec.Group,
 		category:        category,
 		templateFile:    handlerTemplateFile,
 		builtinTemplate: handlerTemplate,
-		data:            handleObj,
+		data: map[string]any{
+			"PkgName":        pkgName,
+			"ImportPackages": genHandlerImports(group, route, rootPkg),
+			"HandlerName":    handler,
+			"RequestType":    util.Title(route.RequestTypeName()),
+			"LogicName":      logicName,
+			"LogicType":      strings.Title(getLogicName(route)),
+			"Call":           strings.Title(strings.TrimSuffix(handler, "Handler")),
+			"HasResp":        len(route.ResponseTypeName()) > 0,
+			"HasRequest":     len(route.RequestTypeName()) > 0,
+			"HasDoc":         len(route.JoinedDoc()) > 0,
+			"Doc":            getDoc(route.JoinedDoc()),
+		},
 	})
 }
 
diff --git a/tools/goctl/api/gogen/genlogic.go b/tools/goctl/api/gogen/genlogic.go
index 28780495..e162eeb6 100644
--- a/tools/goctl/api/gogen/genlogic.go
+++ b/tools/goctl/api/gogen/genlogic.go
@@ -62,7 +62,7 @@ func genLogicByRoute(dir, rootPkg string, cfg *config.Config, group spec.Group,
 		category:        category,
 		templateFile:    logicTemplateFile,
 		builtinTemplate: logicTemplate,
-		data: map[string]string{
+		data: map[string]any{
 			"pkgName":      subDir[strings.LastIndex(subDir, "/")+1:],
 			"imports":      imports,
 			"logic":        strings.Title(logic),
@@ -70,6 +70,8 @@ func genLogicByRoute(dir, rootPkg string, cfg *config.Config, group spec.Group,
 			"responseType": responseString,
 			"returnString": returnString,
 			"request":      requestString,
+			"hasDoc":       len(route.JoinedDoc()) > 0,
+			"doc":          getDoc(route.JoinedDoc()),
 		},
 	})
 }
diff --git a/tools/goctl/api/gogen/genroutes.go b/tools/goctl/api/gogen/genroutes.go
index 8243d5e4..528cad4a 100644
--- a/tools/goctl/api/gogen/genroutes.go
+++ b/tools/goctl/api/gogen/genroutes.go
@@ -71,6 +71,7 @@ type (
 		method  string
 		path    string
 		handler string
+		doc     string
 	}
 )
 
@@ -92,13 +93,24 @@ func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error
 		var gbuilder strings.Builder
 		gbuilder.WriteString("[]rest.Route{")
 		for _, r := range g.routes {
-			fmt.Fprintf(&gbuilder, `
-		{
-			Method:  %s,
-			Path:    "%s",
-			Handler: %s,
-		},`,
-				r.method, r.path, r.handler)
+			var routeString string
+			if len(r.doc) > 0 {
+				routeString = fmt.Sprintf(`
+					{
+						%s
+						Method:  %s,
+						Path:    "%s",
+						Handler: %s,
+					},`, getDoc(r.doc), r.method, r.path, r.handler)
+			} else {
+				routeString = fmt.Sprintf(`
+					{
+						Method:  %s,
+						Path:    "%s",
+						Handler: %s,
+					},`, r.method, r.path, r.handler)
+			}
+			fmt.Fprint(&gbuilder, routeString)
 		}
 
 		var jwt string
@@ -239,6 +251,7 @@ func getRoutes(api *spec.ApiSpec) ([]group, error) {
 				method:  mapping[r.Method],
 				path:    r.Path,
 				handler: handler,
+				doc:     r.JoinedDoc(),
 			})
 		}
 
diff --git a/tools/goctl/api/gogen/handler.tpl b/tools/goctl/api/gogen/handler.tpl
index a6480a23..fce5acc2 100644
--- a/tools/goctl/api/gogen/handler.tpl
+++ b/tools/goctl/api/gogen/handler.tpl
@@ -7,6 +7,7 @@ import (
 	{{.ImportPackages}}
 )
 
+{{if .HasDoc}}{{.Doc}}{{end}}
 func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		{{if .HasRequest}}var req types.{{.RequestType}}
diff --git a/tools/goctl/api/gogen/logic.tpl b/tools/goctl/api/gogen/logic.tpl
index 7c043237..94611c57 100644
--- a/tools/goctl/api/gogen/logic.tpl
+++ b/tools/goctl/api/gogen/logic.tpl
@@ -10,6 +10,7 @@ type {{.logic}} struct {
 	svcCtx *svc.ServiceContext
 }
 
+{{if .hasDoc}}{{.doc}}{{end}}
 func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} {
 	return &{{.logic}}{
 		Logger: logx.WithContext(ctx),
diff --git a/tools/goctl/api/gogen/util.go b/tools/goctl/api/gogen/util.go
index 948b1ee9..5a9bc6c8 100644
--- a/tools/goctl/api/gogen/util.go
+++ b/tools/goctl/api/gogen/util.go
@@ -181,3 +181,11 @@ func golangExpr(ty spec.Type, pkg ...string) string {
 
 	return ""
 }
+
+func getDoc(doc string) string {
+	if len(doc) == 0 {
+		return ""
+	}
+
+	return "// " + strings.Trim(doc, "\"")
+}


Test patch:
diff --git a/tools/goctl/api/gogen/testdata/has_comment_api_test.api b/tools/goctl/api/gogen/testdata/has_comment_api_test.api
index 3bd89f8e..490ecb3e 100644
--- a/tools/goctl/api/gogen/testdata/has_comment_api_test.api
+++ b/tools/goctl/api/gogen/testdata/has_comment_api_test.api
@@ -16,5 +16,11 @@ service A-api {
     @server(
         handler: GreetHandler
     )
-    get /greet/from/:name(Request) returns (Response)
-}
\ No newline at end of file
+    get /greet/from/:name (Request) returns (Response)
+
+    @doc(
+        summary: "comment comment comment"
+    )
+    @handler NoResponseHandler
+    get /greet/get (Request)
+}