-
Notifications
You must be signed in to change notification settings - Fork 249
/
httpiclient.go
109 lines (99 loc) · 2.57 KB
/
httpiclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package codegen
import (
"bufio"
"bytes"
"github.com/sirupsen/logrus"
"github.com/unionj-cloud/go-doudou/cmd/internal/astutils"
"github.com/unionj-cloud/go-doudou/toolkit/copier"
"github.com/unionj-cloud/go-doudou/version"
"os"
"path/filepath"
"strings"
"text/template"
)
var iclientTmpl = `/**
* Generated by go-doudou {{.Version}}.
* Don't edit!
*/
package client
import (
"context"
"github.com/go-resty/resty/v2"
"{{.VoPackage}}"
v3 "github.com/unionj-cloud/go-doudou/toolkit/openapi/v3"
"os"
)
type I{{.Meta.Name}}Client interface {
{{- range $m := .Meta.Methods }}
{{$m.Name}}(ctx context.Context, _headers map[string]string, {{- range $i, $p := $m.Params}}
{{- if ne $p.Type "context.Context" }}
{{- $p.Name}} {{$p.Type}},
{{- end }}
{{- end }}) (_resp *resty.Response, {{- range $i, $r := $m.Results}}
{{- if $i}},{{end}}
{{- $r.Name}} {{$r.Type}}
{{- end }})
{{- end }}
}
`
// GenGoIClient generates golang http client interface code from result of parsing svc.go file in project root path
func GenGoIClient(dir string, ic astutils.InterfaceCollector) {
var (
err error
clientfile string
f *os.File
tpl *template.Template
sqlBuf bytes.Buffer
clientDir string
fi os.FileInfo
source string
modfile string
modName string
firstLine string
modf *os.File
meta astutils.InterfaceMeta
)
clientDir = filepath.Join(dir, "client")
if err = os.MkdirAll(clientDir, os.ModePerm); err != nil {
panic(err)
}
clientfile = filepath.Join(clientDir, "iclient.go")
fi, err = os.Stat(clientfile)
if err != nil && !os.IsNotExist(err) {
panic(err)
}
if fi != nil {
logrus.Warningln("file iclient.go will be overwritten")
}
if f, err = os.Create(clientfile); err != nil {
panic(err)
}
defer f.Close()
err = copier.DeepCopy(ic.Interfaces[0], &meta)
if err != nil {
panic(err)
}
modfile = filepath.Join(dir, "go.mod")
if modf, err = os.Open(modfile); err != nil {
panic(err)
}
reader := bufio.NewReader(modf)
firstLine, _ = reader.ReadString('\n')
modName = strings.TrimSpace(strings.TrimPrefix(firstLine, "module"))
if tpl, err = template.New("iclient.go.tmpl").Parse(iclientTmpl); err != nil {
panic(err)
}
if err = tpl.Execute(&sqlBuf, struct {
VoPackage string
Meta astutils.InterfaceMeta
Version string
}{
VoPackage: modName + "/vo",
Meta: meta,
Version: version.Release,
}); err != nil {
panic(err)
}
source = strings.TrimSpace(sqlBuf.String())
astutils.FixImport([]byte(source), clientfile)
}