Skip to content

Commit

Permalink
optimize plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
northseadl committed Oct 6, 2023
1 parent 281ace2 commit 3aa5f85
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 11 deletions.
6 changes: 4 additions & 2 deletions cmd/devctl/plugin/client.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package {{.PackageName}}

import (
{{if .HasTypesImport}}"{{.TypesImportPath}}"{{end}}
"context"
{{if .HasFmtImport}}"fmt"{{end}}
{{if .HasNetHttpImport}}"net/http"{{end}}
)
Expand All @@ -11,9 +12,10 @@ type {{.GroupName}} struct {
}

{{range .Routes}}
func (c *{{$.GroupName}}) {{.Handler}}({{if ne .RequestTypeName ""}}req *types.{{.RequestTypeName}}{{end}}) (*types.{{.ResponseTypeName}}, error) {
res := &types.{{.ResponseTypeName}}{}
func (c *{{$.GroupName}}) {{.Handler}}(ctx context.Context, {{if ne .RequestTypeName ""}}req *powerxtypes.{{.RequestTypeName}}{{end}}) (*powerxtypes.{{.ResponseTypeName}}, error) {
res := &powerxtypes.{{.ResponseTypeName}}{}
err := c.H.Df().Method(http.Method{{CapFirst .Method}}).
WithContext(ctx).
Uri({{FormatPath .Path .Handler $.PathParamsMap}}).
{{if and (ne (ToUpper .Method) "GET") (ne .RequestTypeName "")}}Json(req).{{else if and (eq (ToUpper .Method) "GET") (ne .RequestTypeName "")}}BindQuery(req).{{end}}
Result(res)
Expand Down
45 changes: 42 additions & 3 deletions cmd/devctl/plugin/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
const (
apiDir = "api"
packageName = "powerx"
typesImportPath = "PluginTemplate/pkg/powerx/types"
typesImportPath = "PluginTemplate/pkg/powerx/powerxtypes"
)

type StringMap = map[string]string
Expand Down Expand Up @@ -46,11 +46,12 @@ func GenerateClientCode(api *spec.ApiSpec, targetDir string) error {
return err
}

tmpl, err := parseTemplate()
tmpl, err := parseClientTemplate()
if err != nil {
return err
}

var apiModules []string
for _, group := range api.Service.Groups {
templateData, err := prepareTemplateData(group)
if err != nil {
Expand All @@ -60,6 +61,17 @@ func GenerateClientCode(api *spec.ApiSpec, targetDir string) error {
if err := generateGroupClientCode(tmpl, targetDir, templateData); err != nil {
return err
}
if templateData.GroupName != "" {
apiModules = append(apiModules, templateData.GroupName)
}
}

tmpl, err = parsePowerXTemple()
if err != nil {
return err
}
if err := generatePowerXCode(tmpl, targetDir, apiModules); err != nil {
return err
}

return nil
Expand All @@ -75,7 +87,7 @@ func createTargetDir(targetDir string) error {
return nil
}

func parseTemplate() (*template.Template, error) {
func parseClientTemplate() (*template.Template, error) {
tmplContent, err := ioutil.ReadFile(GetResourcePath("client.tpl"))
if err != nil {
return nil, fmt.Errorf("error reading client.tpl: %w", err)
Expand All @@ -90,6 +102,14 @@ func parseTemplate() (*template.Template, error) {
return template.New("clientCode").Funcs(funcMap).Parse(string(tmplContent))
}

func parsePowerXTemple() (*template.Template, error) {
tmplContent, err := ioutil.ReadFile(GetResourcePath("powerx.tpl"))
if err != nil {
return nil, fmt.Errorf("error reading powerx.tpl: %w", err)
}
return template.New("powerxCode").Parse(string(tmplContent))
}

func prepareTemplateData(group spec.Group) (TemplateData, error) {
groupName := formatGroupName(group.Annotation.Properties["group"])

Expand Down Expand Up @@ -175,6 +195,25 @@ func generateGroupClientCode(tmpl *template.Template, targetDir string, template
return nil
}

func generatePowerXCode(tmpl *template.Template, targetDir string, apiModules []string) error {
// 如果 groupName 为空,则不生成 client 代码
if len(apiModules) == 0 {
return nil
}
var buf bytes.Buffer
err := tmpl.Execute(&buf, apiModules)
if err != nil {
return fmt.Errorf("error executing client template: %w", err)
}

err = ioutil.WriteFile(filepath.Join(targetDir, "powerx.go"), buf.Bytes(), 0644)
if err != nil {
return fmt.Errorf("error writing client code: %w", err)
}

return nil
}

func GetResourcePath(file string) string {
_, currentFilePath, _, _ := runtime.Caller(0)
currentDir := filepath.Dir(currentFilePath)
Expand Down
22 changes: 22 additions & 0 deletions cmd/devctl/plugin/powerx.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package powerx

import (
"PluginTemplate/pkg/powerx/client"
)

type PowerX struct {
*client.PClient
{{range .}}
{{.}} *{{.}}
{{end}}
}

func NewPowerX(endpoint string, debug bool) *PowerX {
power := &PowerX{
PClient: client.NewPClient(endpoint, debug),
}
{{range .}}
power.{{.}} = &{{.}}{power}
{{end}}
return power
}
8 changes: 4 additions & 4 deletions pkg/pluginx/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,17 +334,17 @@ func mergePluginFiles(pluginDir string, frontDir string) (buildFiles *BuildData,
}
PluginFrontendConfig.Routes = append(PluginFrontendConfig.Routes, route)

fmt.Println(info.Name)

// 复制 frontend/views 目录到 src/views/{插件名} 目录下
err = CopyAndRenameDir(filepath.Join(pluginDir, entry.Name(), "frontend", "views"), filepath.Join(frontDir, "src/views", info.Name))
err = CopyAndRenameDir(filepath.Join(pluginDir, entry.Name(), "frontend/views"), filepath.Join(frontDir, "src/views", info.Name))
if err != nil {
return nil, err
}

// 复制 frontend/module.ts 到 src/router/routes/modules/{插件名}.ts
moduleFilePath := filepath.Join(frontDir, "src/router/routes/modules", info.Name+".ts")
err = CopyAndRenameFile(filepath.Join(pluginDir, entry.Name(), "frontend", "module.ts"), moduleFilePath)
// 替换 module.ts 中的 @/views/plugin 为 @/views/{插件名}
err = ReplaceFileString(moduleFilePath, "@/views/plugin", "@/views/"+info.Name, 1)
err = CopyAndRenameFile(filepath.Join(pluginDir, entry.Name(), "frontend/module.ts"), moduleFilePath)

// 检查 frontend/api 目录下是否存在文件, 如果存在则复制到 src/api 目录下
apiDir := filepath.Join(pluginDir, entry.Name(), "frontend", "api")
Expand Down
5 changes: 4 additions & 1 deletion pkg/pluginx/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ func (m *Manager) ProxyHandleFunc() http.HandlerFunc {
return
}

targetURL := fmt.Sprintf("http://%s/%s", plugin.m.mainHost, pluginPath)
targetURL := fmt.Sprintf("http://%s/%s", plugin.PluginHost, pluginPath)
fmt.Println(targetURL)
if request.URL.RawQuery != "" {
targetURL = targetURL + "?" + request.URL.RawQuery
}
Expand All @@ -91,6 +92,8 @@ func (m *Manager) ProxyHandleFunc() http.HandlerFunc {

copyHeaders(request.Header, proxyReq.Header)

fmt.Println(proxyReq.Header)

resp, err := http.DefaultClient.Do(proxyReq)
if err != nil {
logx.Errorf("Error sending proxy request: %v", err)
Expand Down
5 changes: 4 additions & 1 deletion pkg/pluginx/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ func (s *PluginFrontendServer) Serve(dir string, port string) error {
r.Static("/css", filepath.Join(dir, "css"))
r.Static("/assets", filepath.Join(dir, "assets"))

// api 路由转发, /api -> proxy
r.Any("/api/*path", gin.WrapF(s.ProxyHandleFunc()))

// 单页面应用处理
r.NoRoute(func(c *gin.Context) {
c.File(filepath.Join(dir, "index.html"))
Expand Down Expand Up @@ -63,7 +66,7 @@ func (s *PluginBackendServer) Serve() error {
return fmt.Errorf("plugin already started")
}
// cmd 启动插件, 同时启动一个 goroutine 监听插件的就绪
cmd := exec.Command(s.p.Backend, "-n", s.p.Name, "-h", s.p.m.mainHost)
cmd := exec.Command(s.p.Backend, "-n", s.p.Name, "-h", s.p.m.mainHost, "-m", "prod")
go func() {
for i := 0; i < 10; i++ {
if cmd.Process != nil {
Expand Down

0 comments on commit 3aa5f85

Please sign in to comment.