Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsgen adjust and add phpgen. #4479

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion tools/goctl/api/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package api
import (
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/api/apigen"
"github.com/zeromicro/go-zero/tools/goctl/api/csgen"
"github.com/zeromicro/go-zero/tools/goctl/api/dartgen"
"github.com/zeromicro/go-zero/tools/goctl/api/docgen"
"github.com/zeromicro/go-zero/tools/goctl/api/format"
"github.com/zeromicro/go-zero/tools/goctl/api/gogen"
"github.com/zeromicro/go-zero/tools/goctl/api/javagen"
"github.com/zeromicro/go-zero/tools/goctl/api/ktgen"
"github.com/zeromicro/go-zero/tools/goctl/api/new"
"github.com/zeromicro/go-zero/tools/goctl/api/phpgen"
"github.com/zeromicro/go-zero/tools/goctl/api/tsgen"
"github.com/zeromicro/go-zero/tools/goctl/api/validate"
"github.com/zeromicro/go-zero/tools/goctl/config"
Expand All @@ -31,6 +33,8 @@ var (
ktCmd = cobrax.NewCommand("kt", cobrax.WithRunE(ktgen.KtCommand))
pluginCmd = cobrax.NewCommand("plugin", cobrax.WithRunE(plugin.PluginCommand))
tsCmd = cobrax.NewCommand("ts", cobrax.WithRunE(tsgen.TsCommand))
phpCmd = cobrax.NewCommand("php", cobrax.WithRunE(phpgen.PhpCommand))
csCmd = cobrax.NewCommand("cs", cobrax.WithRunE(csgen.CSharpCommand))
)

func init() {
Expand All @@ -46,6 +50,8 @@ func init() {
pluginCmdFlags = pluginCmd.Flags()
tsCmdFlags = tsCmd.Flags()
validateCmdFlags = validateCmd.Flags()
phpCmdFlags = phpCmd.Flags()
csCmdFlags = csCmd.Flags()
)

apiCmdFlags.StringVar(&apigen.VarStringOutput, "o")
Expand Down Expand Up @@ -95,9 +101,19 @@ func init() {
tsCmdFlags.StringVar(&tsgen.VarStringAPI, "api")
tsCmdFlags.StringVar(&tsgen.VarStringCaller, "caller")
tsCmdFlags.BoolVar(&tsgen.VarBoolUnWrap, "unwrap")
tsCmdFlags.StringVar(&tsgen.VarStringUrlPrefix, "url")
tsCmdFlags.BoolVar(&tsgen.VarBoolCustomBody, "body")

validateCmdFlags.StringVar(&validate.VarStringAPI, "api")

phpCmdFlags.StringVar(&phpgen.VarStringDir, "dir")
phpCmdFlags.StringVar(&phpgen.VarStringAPI, "api")
phpCmdFlags.StringVar(&phpgen.VarStringNS, "ns")

csCmdFlags.StringVar(&csgen.VarStringDir, "dir")
csCmdFlags.StringVar(&csgen.VarStringAPI, "api")
csCmdFlags.StringVar(&csgen.VarStringNS, "ns")

// Add sub-commands
Cmd.AddCommand(dartCmd, docCmd, formatCmd, goCmd, javaCmd, ktCmd, newCmd, pluginCmd, tsCmd, validateCmd)
Cmd.AddCommand(dartCmd, docCmd, formatCmd, goCmd, javaCmd, ktCmd, newCmd, pluginCmd, tsCmd, validateCmd, phpCmd, csCmd)
}
43 changes: 43 additions & 0 deletions tools/goctl/api/csgen/ApiAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class HeaderPropertyName : Attribute
{
public HeaderPropertyName(string name)
{
Name = name;
}

/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
}


[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class PathPropertyName : Attribute
{
public PathPropertyName(string name)
{
Name = name;
}

/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
}


[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class FormPropertyName : Attribute
{
public FormPropertyName(string name)
{
Name = name;
}

/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
}
103 changes: 103 additions & 0 deletions tools/goctl/api/csgen/ApiBaseClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using System.Net.Http.Json;
using System.Reflection;
using System.Web;

public abstract class ApiBaseClient
{
protected readonly HttpClient httpClient = new HttpClient();


public ApiBaseClient(string host, short port, string scheme)
{
httpClient.BaseAddress = new Uri($"{scheme}://{host}:{port}");
}

protected async Task<R> CallResultAsync<R>(HttpMethod method, string path, CancellationToken cancellationToken) where R : new()
{
var response = await CallAsync(HttpMethod.Post, path, cancellationToken);
return await ParseResponseAsync<R>(response);
}

protected async Task<HttpResponseMessage> CallAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
return await httpClient.SendAsync(request, cancellationToken);
}


protected async Task<R> RequestResultAsync<T, R>(HttpMethod method, string path, T? param, CancellationToken cancellationToken) where R : new()
{
var response = await RequestAsync(HttpMethod.Post, path, param, cancellationToken);
return await ParseResponseAsync<R>(response);
}

protected async Task<HttpResponseMessage> RequestAsync<T>(HttpMethod method, string path, T? param, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage();
request.Method = method;
var query = HttpUtility.ParseQueryString(string.Empty);

if (param != null)
{
foreach (var p in param.GetType().GetProperties())
{
var pv = p.GetValue(param);

// 头部
var hpn = p.GetCustomAttribute<HeaderPropertyName>();
if (hpn != null)
{
request.Headers.Add(hpn.Name, pv?.ToString() ?? "");
continue;
}

// 请求参数
var fpn = p.GetCustomAttribute<FormPropertyName>();
if (fpn != null)
{
query.Add(fpn.Name, pv?.ToString() ?? "");
continue;
}

// 路径参数
var ppn = p.GetCustomAttribute<PathPropertyName>();
if (ppn != null)
{
path.Replace($":{ppn.Name}", pv?.ToString() ?? "");
continue;
}
}

// 请求链接
request.RequestUri = new Uri(httpClient.BaseAddress!, query.Count > 0 ? $"{path}?{query}" : path);

// JSON 内容
if (HttpMethod.Get != method)
{
request.Content = JsonContent.Create(param);
}
}

return await httpClient.SendAsync(request, cancellationToken);
}

protected static async Task<R> ParseResponseAsync<R>(HttpResponseMessage response) where R : new()
{
R result = await response.Content.ReadFromJsonAsync<R>() ?? new R();
foreach (var p in typeof(R).GetProperties())
{
// 头部
var hpn = p.GetCustomAttribute<HeaderPropertyName>();
if (hpn != null && response.Headers.Contains(hpn.Name))
{
var v = response.Headers.GetValues(hpn.Name);
if (v != null && v.Count() > 0)
{
p.SetValue(result, v.First());
}
continue;
}
}
return result;
}
}
108 changes: 108 additions & 0 deletions tools/goctl/api/csgen/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package csgen

import (
"fmt"
"os"
"path/filepath"
"strings"

_ "embed"

"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)

//go:embed ApiAttribute.cs
var apiAttributeTemplate string

//go:embed ApiBaseClient.cs
var apiApiBaseClientTemplate string

func genClient(dir string, ns string, api *spec.ApiSpec) error {
if err := writeTemplate(dir, ns, "ApiAttribute", apiAttributeTemplate); err != nil {
return err
}
if err := writeTemplate(dir, ns, "ApiBaseClient", apiApiBaseClientTemplate); err != nil {
return err
}

return writeClient(dir, ns, api)
}

func writeTemplate(dir string, ns string, name string, template string) error {
fp := filepath.Join(dir, fmt.Sprintf("%s.cs", name))
f, err := os.OpenFile(fp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
defer f.Close()
fmt.Fprintf(f, "namespace %s;\r\n\r\n", ns)
fmt.Fprint(f, template)
return nil
}

func writeClient(dir string, ns string, api *spec.ApiSpec) error {
name := camelCase(api.Service.Name, true)
fp := filepath.Join(dir, fmt.Sprintf("%sClient.cs", name))
f, err := os.OpenFile(fp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
defer f.Close()

fmt.Fprintf(f, "namespace %s;\r\n\r\n", ns)

// 类
fmt.Fprintf(f, "public sealed class %sClient : ApiBaseClient\r\n{\r\n", name)

// 构造函数
fmt.Fprintf(f, " public %sClient(string host, short port, string scheme = \"http\") : base(host, port, scheme){}\r\n", name)

// 组
for _, g := range api.Service.Groups {
prefix := g.GetAnnotation("prefix")
p := camelCase(prefix, true)

// 路由
for _, r := range g.Routes {
an := camelCase(r.Path, true)
method := upperHead(strings.ToLower(r.Method), 1)

writeIndent(f, 4)
fmt.Fprint(f, "public async ")
if r.ResponseType != nil {
fmt.Fprintf(f, "Task<%s>", r.ResponseType.Name())
} else {
fmt.Fprint(f, "Task<HttpResponseMessage>")
}
fmt.Fprintf(f, " %s%s%sAsync(", method, p, an)
if r.RequestType != nil {
fmt.Fprintf(f, "%s request,", r.RequestType.Name())
}
fmt.Fprint(f, "CancellationToken cancellationToken)\r\n {\r\n")

writeIndent(f, 8)
fmt.Fprint(f, "return await ")

if r.RequestType != nil {
if r.ResponseType != nil {
fmt.Fprintf(f, "RequestResultAsync<%s,%s>(HttpMethod.%s, \"%s\", request, cancellationToken);\r\n", r.RequestType.Name(), r.ResponseType.Name(), method, r.Path)
} else {
fmt.Fprintf(f, "RequestAsync(HttpMethod.%s, \"%s\", request, cancellationToken);\r\n", method, r.Path)
}
} else {
if r.ResponseType != nil {
fmt.Fprintf(f, "CallResultAsync<%s>(HttpMethod.%s, \"%s\", cancellationToken);\r\n", r.ResponseType.Name(), method, r.Path)
} else {
fmt.Fprintf(f, "CallAsync(HttpMethod.%s, \"%s\", cancellationToken);\r\n", method, r.Path)
}
}

writeIndent(f, 4)
fmt.Fprint(f, "}\r\n")
}
}

fmt.Fprint(f, "}\r\n")

return nil
}
53 changes: 53 additions & 0 deletions tools/goctl/api/csgen/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package csgen

import (
"errors"
"fmt"

"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)

var (
// VarStringDir describes a directory.
VarStringDir string
// VarStringAPI describes an API file.
VarStringAPI string
// VarStringAPI describes an C# namespace.
VarStringNS string
)

func CSharpCommand(_ *cobra.Command, _ []string) error {
apiFile := VarStringAPI
if apiFile == "" {
return errors.New("missing -api")
}
dir := VarStringDir
if dir == "" {
return errors.New("missing -dir")
}

ns := VarStringNS
if ns == "" {
return errors.New("missing -ns")
}

api, e := parser.Parse(apiFile)
if e != nil {
return e
}

if err := api.Validate(); err != nil {
return err
}

logx.Must(pathx.MkdirIfNotExist(dir))
logx.Must(genMessages(dir, ns, api))
logx.Must(genClient(dir, ns, api))

fmt.Println(color.Green.Render("Done."))
return nil
}
Loading