refactor middleware generator (#159)
* rebase upstream * rebase * trim no need line * trim no need line * trim no need line * update doc * remove update * remove no need * remove no need * goctl add jwt support * goctl add jwt support * goctl add jwt support * goctl support import * goctl support import * support return () * revert * refactor and rename folder to group * remove no need * add anonymous annotation * optimized * rename * rename * update test * api add middleware support: usage: @server( middleware: M1, M2 ) * api add middleware support: usage: @server( middleware: M1, M2 ) * simple logic * optimized * optimized generator formatted code * optimized generator formatted code * add more test * refactor middleware generator * revert test * revert test * revert test * revert test * revert test Co-authored-by: kingxt <dream4kingxt@163.com>master
parent
db7dcaa120
commit
1c9e81aa28
@ -0,0 +1,59 @@
|
||||
package gogen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/tal-tech/go-zero/tools/goctl/api/util"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
func genMiddleware(dir string, middlewares []string) error {
|
||||
for _, item := range middlewares {
|
||||
filename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "middleware" + ".go"
|
||||
fp, created, err := util.MaybeCreateFile(dir, middlewareDir, filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !created {
|
||||
return nil
|
||||
}
|
||||
defer fp.Close()
|
||||
|
||||
name := strings.TrimSuffix(item, "Middleware") + "Middleware"
|
||||
t := template.Must(template.New("contextTemplate").Parse(middlewareImplementCode))
|
||||
buffer := new(bytes.Buffer)
|
||||
err = t.Execute(buffer, map[string]string{
|
||||
"name": strings.Title(name),
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
formatCode := formatCode(buffer.String())
|
||||
_, err = fp.WriteString(formatCode)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
Loading…
Reference in New Issue