feat: use go:embed to embed templates (#1756)

This commit is contained in:
Kevin Wan
2022-04-04 13:12:05 +08:00
committed by GitHub
parent 58a0b17451
commit faad6e27e3
60 changed files with 739 additions and 691 deletions

View File

@@ -0,0 +1,24 @@
syntax = "v1"
info (
title: // TODO: add title
desc: // TODO: add description
author: "{{.gitUser}}"
email: "{{.gitEmail}}"
)
type request {
// TODO: add members here and delete this comment
}
type response {
// TODO: add members here and delete this comment
}
service {{.serviceName}} {
@handler GetUser // TODO: set handler name and delete this comment
get /users/id/:userId(request) returns(response)
@handler CreateUser // TODO: set handler name and delete this comment
post /users/create(request)
}

View File

@@ -1,11 +1,12 @@
package apigen
import (
_ "embed"
"errors"
"fmt"
"html/template"
"path/filepath"
"strings"
"text/template"
"github.com/logrusorgru/aurora"
"github.com/urfave/cli"
@@ -13,32 +14,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const apiTemplate = `
syntax = "v1"
info (
title: // TODO: add title
desc: // TODO: add description
author: "{{.gitUser}}"
email: "{{.gitEmail}}"
)
type request {
// TODO: add members here and delete this comment
}
type response {
// TODO: add members here and delete this comment
}
service {{.serviceName}} {
@handler GetUser // TODO: set handler name and delete this comment
get /users/id/:userId(request) returns(response)
@handler CreateUser // TODO: set handler name and delete this comment
post /users/create(request)
}
`
//go:embed api.tpl
var apiTemplate string
// ApiCommand create api template file
func ApiCommand(c *cli.Context) error {

View File

@@ -2,6 +2,7 @@ package docgen
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"strconv"
@@ -13,25 +14,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/api/util"
)
const (
markdownTemplate = `
### {{.index}}. {{.routeComment}}
1. 路由定义
- Url: {{.uri}}
- Method: {{.method}}
- Request: {{.requestType}}
- Response: {{.responseType}}
2. 请求定义
{{.requestContent}}
3. 返回定义
{{.responseContent}}
`
)
//go:embed markdown.tpl
var markdownTemplate string
func genDoc(api *spec.ApiSpec, dir, filename string) error {
fp, _, err := util.MaybeCreateFile(dir, "", filename)

View File

@@ -0,0 +1,16 @@
### {{.index}}. {{.routeComment}}
1. route definition
- Url: {{.uri}}
- Method: {{.method}}
- Request: {{.requestType}}
- Response: {{.responseType}}
2. request definition
{{.requestContent}}
3. response definition
{{.responseContent}}

View File

@@ -0,0 +1,3 @@
Name: {{.serviceName}}
Host: {{.host}}
Port: {{.port}}

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"strconv"
@@ -12,12 +13,11 @@ import (
const (
defaultPort = 8888
etcDir = "etc"
etcTemplate = `Name: {{.serviceName}}
Host: {{.host}}
Port: {{.port}}
`
)
//go:embed etc.tpl
var etcTemplate string
func genEtc(dir string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, api.Service.Name)
if err != nil {

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"path"
"strings"
@@ -14,36 +15,10 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const (
defaultLogicPackage = "logic"
handlerTemplate = `package {{.PkgName}}
const defaultLogicPackage = "logic"
import (
"net/http"
{{if .After1_1_10}}"github.com/zeromicro/go-zero/rest/httpx"{{end}}
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
{{if .HasRequest}}var req types.{{.RequestType}}
if err := httpx.Parse(r, &req); err != nil {
httpx.Error(w, err)
return
}
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
if err != nil {
httpx.Error(w, err)
} else {
{{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
}
}
}
`
)
//go:embed handler.tpl
var handlerTemplate string
type handlerInfo struct {
PkgName string

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"path"
"strconv"
@@ -14,32 +15,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const logicTemplate = `package {{.pkgName}}
import (
{{.imports}}
)
type {{.logic}} struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} {
return &{{.logic}}{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} {
// todo: add your logic here and delete this line
{{.returnString}}
}
`
//go:embed logic.tpl
var logicTemplate string
func genLogic(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
for _, g := range api.Service.Groups {

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"strings"
@@ -11,33 +12,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const mainTemplate = `package main
import (
"flag"
"fmt"
{{.importPackages}}
)
var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}
`
//go:embed main.tpl
var mainTemplate string
func genMain(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
name := strings.ToLower(api.Service.Name)

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
@@ -8,27 +9,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/format"
)
var middlewareImplementCode = `
package middleware
import "net/http"
type {{.name}} struct {
}
func New{{.name}}() *{{.name}} {
return &{{.name}}{}
}
func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO generate middleware implement function, delete after code implementation
// Passthrough to next handler if need
next(w, r)
}
}
`
//go:embed middleware.tpl
var middlewareImplementCode string
func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error {
middlewares := getMiddleware(api)

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"strings"
@@ -11,27 +12,10 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const (
contextFilename = "service_context"
contextTemplate = `package svc
const contextFilename = "service_context"
import (
{{.configImport}}
)
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
}
func NewServiceContext(c {{.config}}) *ServiceContext {
return &ServiceContext{
Config: c,
{{.middlewareAssignment}}
}
}
`
)
//go:embed svc.tpl
var contextTemplate string
func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)

View File

@@ -1,6 +1,7 @@
package gogen
import (
_ "embed"
"fmt"
"io"
"os"
@@ -14,16 +15,10 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/format"
)
const (
typesFile = "types"
typesTemplate = `// Code generated by goctl. DO NOT EDIT.
package types{{if .containsTime}}
import (
"time"
){{end}}
{{.types}}
`
)
const typesFile = "types"
//go:embed types.tpl
var typesTemplate string
// BuildTypes gen types to string
func BuildTypes(types []spec.Type) (string, error) {

View File

@@ -0,0 +1,26 @@
package {{.PkgName}}
import (
"net/http"
{{if .After1_1_10}}"github.com/zeromicro/go-zero/rest/httpx"{{end}}
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
{{if .HasRequest}}var req types.{{.RequestType}}
if err := httpx.Parse(r, &req); err != nil {
httpx.Error(w, err)
return
}
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
if err != nil {
httpx.Error(w, err)
} else {
{{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
}
}
}

View File

@@ -0,0 +1,25 @@
package {{.pkgName}}
import (
{{.imports}}
)
type {{.logic}} struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} {
return &{{.logic}}{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} {
// todo: add your logic here and delete this line
{{.returnString}}
}

View File

@@ -0,0 +1,26 @@
package main
import (
"flag"
"fmt"
{{.importPackages}}
)
var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

View File

@@ -0,0 +1,19 @@
package middleware
import "net/http"
type {{.name}} struct {
}
func New{{.name}}() *{{.name}} {
return &{{.name}}{}
}
func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO generate middleware implement function, delete after code implementation
// Passthrough to next handler if need
next(w, r)
}
}

View File

@@ -0,0 +1,17 @@
package svc
import (
{{.configImport}}
)
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
}
func NewServiceContext(c {{.config}}) *ServiceContext {
return &ServiceContext{
Config: c,
{{.middlewareAssignment}}
}
}

View File

@@ -0,0 +1,6 @@
// Code generated by goctl. DO NOT EDIT.
package types{{if .containsTime}}
import (
"time"
){{end}}
{{.types}}

View File

@@ -0,0 +1,9 @@
{{.indent}}{{.decorator}}
{{.indent}}public {{.returnType}} is{{.property}}() {
{{.indent}} return this.{{.tagValue}};
{{.indent}}}
{{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
{{.indent}} this.{{.tagValue}} = {{.propertyValue}};
{{.indent}}}

View File

@@ -0,0 +1,22 @@
// Code generated by goctl. DO NOT EDIT.
package com.xhb.logic.http.packet.{{.packet}}.model;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
{{.imports}}
public class {{.className}} extends {{.superClassName}} {
{{.properties}}
{{if .HasProperty}}
public {{.className}}() {
}
public {{.className}}({{.params}}) {
{{.constructorSetter}}
}
{{end}}
{{.getSet}}
}

View File

@@ -12,7 +12,7 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
// JavaCommand the generate java code command entrance
// JavaCommand generates java code command entrance.
func JavaCommand(c *cli.Context) error {
apiFile := c.String("api")
dir := c.String("dir")

View File

@@ -3,6 +3,7 @@ package javagen
import (
"bufio"
"bytes"
_ "embed"
"errors"
"fmt"
"io"
@@ -18,54 +19,19 @@ import (
)
const (
componentTemplate = `// Code generated by goctl. DO NOT EDIT.
package com.xhb.logic.http.packet.{{.packet}}.model;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
{{.imports}}
public class {{.className}} extends {{.superClassName}} {
{{.properties}}
{{if .HasProperty}}
public {{.className}}() {
}
public {{.className}}({{.params}}) {
{{.constructorSetter}}
}
{{end}}
{{.getSet}}
}
`
getSetTemplate = `
{{.indent}}{{.decorator}}
{{.indent}}public {{.returnType}} get{{.property}}() {
{{.indent}} return this.{{.tagValue}};
{{.indent}}}
{{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
{{.indent}} this.{{.tagValue}} = {{.propertyValue}};
{{.indent}}}
`
boolTemplate = `
{{.indent}}{{.decorator}}
{{.indent}}public {{.returnType}} is{{.property}}() {
{{.indent}} return this.{{.tagValue}};
{{.indent}}}
{{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
{{.indent}} this.{{.tagValue}} = {{.propertyValue}};
{{.indent}}}
`
httpResponseData = "import com.xhb.core.response.HttpResponseData;"
httpData = "import com.xhb.core.packet.HttpData;"
)
var (
//go:embed component.tpl
componentTemplate string
//go:embed getset.tpl
getSetTemplate string
//go:embed bool.tpl
boolTemplate string
)
type componentsContext struct {
api *spec.ApiSpec
requestTypes []spec.Type

View File

@@ -2,6 +2,7 @@ package javagen
import (
"bytes"
_ "embed"
"fmt"
"strings"
"text/template"
@@ -12,32 +13,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util"
)
const packetTemplate = `package com.xhb.logic.http.packet.{{.packet}};
import com.xhb.core.packet.HttpPacket;
import com.xhb.core.network.HttpRequestClient;
{{.imports}}
{{.doc}}
public class {{.packetName}} extends HttpPacket<{{.responseType}}> {
{{.paramsDeclaration}}
public {{.packetName}}({{.params}}{{if .HasRequestBody}}{{.requestType}} request{{end}}) {
{{if .HasRequestBody}}super(request);{{else}}super(EmptyRequest.instance);{{end}}
{{if .HasRequestBody}}this.request = request;{{end}}{{.paramsSetter}}
}
@Override
public HttpRequestClient.Method requestMethod() {
return HttpRequestClient.Method.{{.method}};
}
@Override
public String requestUri() {
return {{.uri}};
}
}
`
//go:embed packet.tpl
var packetTemplate string
func genPacket(dir, packetName string, api *spec.ApiSpec) error {
for _, route := range api.Service.Routes() {

View File

@@ -0,0 +1,9 @@
{{.indent}}{{.decorator}}
{{.indent}}public {{.returnType}} get{{.property}}() {
{{.indent}} return this.{{.tagValue}};
{{.indent}}}
{{.indent}}public void set{{.property}}({{.type}} {{.propertyValue}}) {
{{.indent}} this.{{.tagValue}} = {{.propertyValue}};
{{.indent}}}

View File

@@ -0,0 +1,25 @@
package com.xhb.logic.http.packet.{{.packet}};
import com.xhb.core.packet.HttpPacket;
import com.xhb.core.network.HttpRequestClient;
{{.imports}}
{{.doc}}
public class {{.packetName}} extends HttpPacket<{{.responseType}}> {
{{.paramsDeclaration}}
public {{.packetName}}({{.params}}{{if .HasRequestBody}}{{.requestType}} request{{end}}) {
{{if .HasRequestBody}}super(request);{{else}}super(EmptyRequest.instance);{{end}}
{{if .HasRequestBody}}this.request = request;{{end}}{{.paramsSetter}}
}
@Override
public HttpRequestClient.Method requestMethod() {
return HttpRequestClient.Method.{{.method}};
}
@Override
public String requestUri() {
return {{.uri}};
}
}

View File

@@ -0,0 +1,22 @@
package {{with .Info}}{{.Desc}}{{end}}
import com.google.gson.Gson
object {{with .Info}}{{.Title}}{{end}}{
{{range .Types}}
data class {{.Name}}({{$length := (len .Members)}}{{range $i,$item := .Members}}
val {{with $item}}{{lowCamelCase .Name}}: {{parseType .Type.Name}}{{end}}{{if ne $i (add $length -1)}},{{end}}{{end}}
){{end}}
{{with .Service}}
{{range .Routes}}suspend fun {{routeToFuncName .Method .Path}}({{with .RequestType}}{{if ne .Name ""}}
req:{{.Name}},{{end}}{{end}}
onOk: (({{with .ResponseType}}{{.Name}}{{end}}) -> Unit)? = null,
onFail: ((String) -> Unit)? = null,
eventually: (() -> Unit)? = null
){
apiRequest("{{upperCase .Method}}","{{.Path}}",{{with .RequestType}}{{if ne .Name ""}}body=req,{{end}}{{end}} onOk = { {{with .ResponseType}}
onOk?.invoke({{if ne .Name ""}}Gson().fromJson(it,{{.Name}}::class.java){{end}}){{end}}
}, onFail = onFail, eventually =eventually)
}
{{end}}{{end}}
}

View File

@@ -0,0 +1,61 @@
package {{.}}
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
const val SERVER = "http://localhost:8080"
suspend fun apiRequest(
method: String,
uri: String,
body: Any = "",
onOk: ((String) -> Unit)? = null,
onFail: ((String) -> Unit)? = null,
eventually: (() -> Unit)? = null
) = withContext(Dispatchers.IO) {
val url = URL(SERVER + uri)
with(url.openConnection() as HttpURLConnection) {
connectTimeout = 3000
requestMethod = method
doInput = true
if (method == "POST" || method == "PUT" || method == "PATCH") {
setRequestProperty("Content-Type", "application/json")
doOutput = true
val data = when (body) {
is String -> {
body
}
else -> {
Gson().toJson(body)
}
}
val wr = OutputStreamWriter(outputStream)
wr.write(data)
wr.flush()
}
try {
if (responseCode >= 400) {
BufferedReader(InputStreamReader(errorStream)).use {
val response = it.readText()
onFail?.invoke(response)
}
return@with
}
//response
BufferedReader(InputStreamReader(inputStream)).use {
val response = it.readText()
onOk?.invoke(response)
}
} catch (e: Exception) {
e.message?.let { onFail?.invoke(it) }
}
}
eventually?.invoke()
}

View File

@@ -7,7 +7,7 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
)
// KtCommand the generate kotlin code command entrance
// KtCommand generates kotlin code command entrance
func KtCommand(c *cli.Context) error {
apiFile := c.String("api")
if apiFile == "" {

View File

@@ -1,6 +1,7 @@
package ktgen
import (
_ "embed"
"fmt"
"os"
"path/filepath"
@@ -10,91 +11,11 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
const (
apiBaseTemplate = `package {{.}}
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
const val SERVER = "http://localhost:8080"
suspend fun apiRequest(
method: String,
uri: String,
body: Any = "",
onOk: ((String) -> Unit)? = null,
onFail: ((String) -> Unit)? = null,
eventually: (() -> Unit)? = null
) = withContext(Dispatchers.IO) {
val url = URL(SERVER + uri)
with(url.openConnection() as HttpURLConnection) {
connectTimeout = 3000
requestMethod = method
doInput = true
if (method == "POST" || method == "PUT" || method == "PATCH") {
setRequestProperty("Content-Type", "application/json")
doOutput = true
val data = when (body) {
is String -> {
body
}
else -> {
Gson().toJson(body)
}
}
val wr = OutputStreamWriter(outputStream)
wr.write(data)
wr.flush()
}
try {
if (responseCode >= 400) {
BufferedReader(InputStreamReader(errorStream)).use {
val response = it.readText()
onFail?.invoke(response)
}
return@with
}
//response
BufferedReader(InputStreamReader(inputStream)).use {
val response = it.readText()
onOk?.invoke(response)
}
} catch (e: Exception) {
e.message?.let { onFail?.invoke(it) }
}
}
eventually?.invoke()
}
`
apiTemplate = `package {{with .Info}}{{.Desc}}{{end}}
import com.google.gson.Gson
object {{with .Info}}{{.Title}}{{end}}{
{{range .Types}}
data class {{.Name}}({{$length := (len .Members)}}{{range $i,$item := .Members}}
val {{with $item}}{{lowCamelCase .Name}}: {{parseType .Type.Name}}{{end}}{{if ne $i (add $length -1)}},{{end}}{{end}}
){{end}}
{{with .Service}}
{{range .Routes}}suspend fun {{routeToFuncName .Method .Path}}({{with .RequestType}}{{if ne .Name ""}}
req:{{.Name}},{{end}}{{end}}
onOk: (({{with .ResponseType}}{{.Name}}{{end}}) -> Unit)? = null,
onFail: ((String) -> Unit)? = null,
eventually: (() -> Unit)? = null
){
apiRequest("{{upperCase .Method}}","{{.Path}}",{{with .RequestType}}{{if ne .Name ""}}body=req,{{end}}{{end}} onOk = { {{with .ResponseType}}
onOk?.invoke({{if ne .Name ""}}Gson().fromJson(it,{{.Name}}::class.java){{end}}){{end}}
}, onFail = onFail, eventually =eventually)
}
{{end}}{{end}}
}`
var (
//go:embed apibase.tpl
apiBaseTemplate string
//go:embed api.tpl
apiTemplate string
)
func genBase(dir, pkg string, api *spec.ApiSpec) error {

View File

@@ -0,0 +1,12 @@
type Request {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response {
Message string ` + "`" + `json:"message"` + "`" + `
}
service {{.name}}-api {
@handler {{.handler}}Handler
get /from/:name(Request) returns (Response)
}

View File

@@ -1,11 +1,12 @@
package new
import (
_ "embed"
"errors"
"html/template"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/urfave/cli"
"github.com/zeromicro/go-zero/tools/goctl/api/gogen"
@@ -14,20 +15,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const apiTemplate = `
type Request {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response {
Message string ` + "`" + `json:"message"` + "`" + `
}
service {{.name}}-api {
@handler {{.handler}}Handler
get /from/:name(Request) returns (Response)
}
`
//go:embed api.tpl
var apiTemplate string
// CreateServiceCommand fast create service
func CreateServiceCommand(c *cli.Context) error {

View File

@@ -0,0 +1,3 @@
/ Code generated by goctl. DO NOT EDIT.
{{.componentTypes}}

View File

@@ -1,6 +1,7 @@
package tsgen
import (
_ "embed"
"path"
"strings"
"text/template"
@@ -10,12 +11,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
componentsTemplate = `// Code generated by goctl. DO NOT EDIT.
{{.componentTypes}}
`
)
//go:embed components.tpl
var componentsTemplate string
func genComponents(dir string, api *spec.ApiSpec) error {
types := api.Types

View File

@@ -1,6 +1,7 @@
package tsgen
import (
_ "embed"
"fmt"
"path"
"strings"
@@ -12,12 +13,8 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
handlerTemplate = `{{.imports}}
{{.apis}}
`
)
//go:embed handler.tpl
var handlerTemplate string
func genHandler(dir, webAPI, caller string, api *spec.ApiSpec, unwrapAPI bool) error {
filename := strings.Replace(api.Service.Name, "-api", "", 1) + ".ts"

View File

@@ -0,0 +1,3 @@
{{.imports}}
{{.apis}}