genmiddleware.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package gogen
  2. import (
  3. "strings"
  4. "git.i2edu.net/i2/go-zero/tools/goctl/api/spec"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  6. "git.i2edu.net/i2/go-zero/tools/goctl/util/format"
  7. )
  8. var middlewareImplementCode = `
  9. package middleware
  10. import "net/http"
  11. type {{.name}} struct {
  12. }
  13. func New{{.name}}() *{{.name}} {
  14. return &{{.name}}{}
  15. }
  16. func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc {
  17. return func(w http.ResponseWriter, r *http.Request) {
  18. // TODO generate middleware implement function, delete after code implementation
  19. // Passthrough to next handler if need
  20. next(w, r)
  21. }
  22. }
  23. `
  24. func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error {
  25. middlewares := getMiddleware(api)
  26. for _, item := range middlewares {
  27. middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware"
  28. filename, err := format.FileNamingFormat(cfg.NamingFormat, middlewareFilename)
  29. if err != nil {
  30. return err
  31. }
  32. name := strings.TrimSuffix(item, "Middleware") + "Middleware"
  33. err = genFile(fileGenConfig{
  34. dir: dir,
  35. subdir: middlewareDir,
  36. filename: filename + ".go",
  37. templateName: "contextTemplate",
  38. builtinTemplate: middlewareImplementCode,
  39. data: map[string]string{
  40. "name": strings.Title(name),
  41. },
  42. })
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. return nil
  48. }