Documentation
¶
Index ¶
- Constants
- Variables
- func IsDefaultPackageTpl(name string) bool
- func MapSerializer(serializer string) string
- func SetDefaultTemplateConfig()
- type Backend
- type Client
- type ClientConfig
- type ClientFile
- type ClientMethod
- type CustomizedFileForIDL
- type CustomizedFileForMethod
- type CustomizedFileForService
- type File
- type FilePathRenderInfo
- type GolangBackend
- type Handler
- type HttpMethod
- type HttpPackage
- type HttpPackageGenerator
- type IDLPackageRenderInfo
- type Layout
- type LayoutGenerator
- type Option
- type RegisterInfo
- type Router
- type RouterNode
- func (routerNode *RouterNode) DFS(i int, hook func(layer int, node *RouterNode) error) error
- func (routerNode *RouterNode) DyeGroupName(snakeStyleMiddleware bool) error
- func (routerNode *RouterNode) FindNearest(paths []string, method string, sortRouter bool) (*RouterNode, int)
- func (routerNode *RouterNode) Insert(name string, method *HttpMethod, handlerType string, paths []string, ...)
- func (routerNode *RouterNode) RawGroupMiddleware() string
- func (routerNode *RouterNode) RawGroupName() string
- func (routerNode *RouterNode) RawHandlerMiddleware() string
- func (routerNode *RouterNode) RawHandlerName() string
- func (routerNode *RouterNode) Sort()
- func (routerNode *RouterNode) Update(method *HttpMethod, handlerType, handlerPkg string, sortRouter bool) error
- type Service
- type SingleHandler
- type Template
- type TemplateConfig
- type TemplateGenerator
- func (tg *TemplateGenerator) Degenerate() error
- func (tg *TemplateGenerator) Files() []File
- func (tg *TemplateGenerator) Generate(input interface{}, tplName, filepath string, noRepeat bool) error
- func (tg *TemplateGenerator) GetFormatAndExcludedFiles() ([]File, error)
- func (tg *TemplateGenerator) Init() error
- func (tg *TemplateGenerator) Persist() error
- type UpdateBehavior
Constants ¶
const ( Skip = "skip" // do not modify existing file Cover = "cover" // overwrite existing file completely Append = "append" // append new content (e.g. new handler methods) to existing file )
UpdateBehavior type constants control how existing files are handled during "update" command.
const (
RegisterFile = "router_gen.go"
)
Variables ¶
var DefaultDelimiters = [2]string{"{{", "}}"}
Functions ¶
func IsDefaultPackageTpl ¶ added in v0.5.1
func MapSerializer ¶
func SetDefaultTemplateConfig ¶
func SetDefaultTemplateConfig()
Types ¶
type Backend ¶
type Backend interface {
Template() (*template.Template, error)
List() map[string]string // returns template name -> body mapping
SetOption(opts string) error // configures generation options (e.g. MarshalEnumToText)
GetOptions() []string // returns active options
Funcs(name string, fn interface{}) error // registers custom template functions
}
Backend abstracts the target language for model code generation. Currently only Go is implemented; third-party backends are planned but not yet supported.
type ClientConfig ¶ added in v0.9.0
type ClientConfig struct {
QueryEnumAsInt bool
}
type ClientFile ¶ added in v0.5.0
type ClientFile struct {
Config ClientConfig
FilePath string
PackageName string
ServiceName string
BaseDomain string
Imports map[string]*model.Model
ClientMethods []*ClientMethod
}
type ClientMethod ¶ added in v0.5.0
type ClientMethod struct {
*HttpMethod
BodyParamsCode string
QueryParamsCode string
PathParamsCode string
HeaderParamsCode string
FormValueCode string
FormFileCode string
}
ClientMethod extends HttpMethod with generated code snippets for building HTTP requests (setting body, query, path params, etc.).
type CustomizedFileForIDL ¶ added in v0.5.1
type CustomizedFileForIDL struct {
*IDLPackageRenderInfo
FilePath string
FilePackage string
}
type CustomizedFileForMethod ¶ added in v0.5.1
type CustomizedFileForMethod struct {
*HttpMethod
FilePath string
FilePackage string
ServiceInfo *Service // service info for this method
IDLPackageInfo *IDLPackageRenderInfo // IDL info for this service
}
type CustomizedFileForService ¶ added in v0.5.1
type CustomizedFileForService struct {
*Service
FilePath string
FilePackage string
IDLPackageInfo *IDLPackageRenderInfo // IDL info for this service
}
type File ¶
type File struct {
Path string // relative output path
Content string // rendered file content
NoRepeat bool // if true, skip writing when file already exists
FileTplName string // source template name (used to determine update warnings)
}
File represents a generated output file pending write to disk.
type FilePathRenderInfo ¶ added in v0.5.1
type FilePathRenderInfo struct {
MasterIDLName string // master IDL name
GenPackage string // master IDL generate code package
HandlerDir string // handler generate dir
ModelDir string // model generate dir
RouterDir string // router generate dir
ProjectDir string // projectDir
GoModule string // go module
ServiceName string // service name, changed as services are traversed
MethodName string // method name, changed as methods are traversed
HandlerGenPath string // "api.gen_path" value
}
type GolangBackend ¶
type GolangBackend struct{}
func (*GolangBackend) Funcs ¶
func (gb *GolangBackend) Funcs(name string, fn interface{}) error
func (*GolangBackend) GetOptions ¶
func (gb *GolangBackend) GetOptions() []string
func (*GolangBackend) List ¶
func (gb *GolangBackend) List() map[string]string
func (*GolangBackend) SetOption ¶
func (gb *GolangBackend) SetOption(opts string) error
type Handler ¶
type HttpMethod ¶
type HttpMethod struct {
Name string
HTTPMethod string // GET, POST, PUT, DELETE, etc.
Comment string // doc comment (formatted by InitComment)
RequestTypeName string // Go type name for request struct
RequestTypePackage string // import path for request type
RequestTypeRawName string // original IDL name before Go conversion
ReturnTypeName string // Go type name for response struct
ReturnTypePackage string // import path for response type
ReturnTypeRawName string // original IDL name before Go conversion
Path string // HTTP route path (e.g. "/api/v1/users/:id")
Serializer string // serialization format: JSON, Thrift, ProtoBuf
OutputDir string // handler output subdirectory (for handler_by_method mode)
RefPackage string // handler import path (set during router tree construction)
RefPackageAlias string // handler import alias
ModelPackage map[string]string // model package aliases
GenHandler bool // false to skip handler generation (dedup for multi-method IDL)
Models map[string]*model.Model // all model dependencies for this method
}
HttpMethod represents a single API endpoint parsed from IDL annotations. One IDL method may map to multiple HTTP methods (e.g. GET + POST), in which case GenHandler is true only for the first to avoid duplicate handler functions.
func (*HttpMethod) InitComment ¶
func (m *HttpMethod) InitComment()
InitComment formats the method comment as a Go doc comment with @router annotation. The @router tag is used by swagger-like tools to document the endpoint.
type HttpPackage ¶
type HttpPackageGenerator ¶
type HttpPackageGenerator struct {
ConfigPath string // path to custom package template YAML config
Backend meta.Backend // model code generation backend (e.g. "golang")
Options []Option // model generation options (e.g. MarshalEnumToText)
CmdType string // current command: new/update/model/client
ProjPackage string // Go module path (e.g. "github.com/foo/bar")
HandlerDir string // relative path for handler output
RouterDir string // relative path for router output
ModelDir string // relative path for model output (e.g. "biz/model")
UseDir string // external model package to import instead of generating
ClientDir string // client output dir for "new"/"update" commands
IdlClientDir string // default client dir derived from IDL namespace (for "client" command)
ForceClientDir string // client dir without IDL namespace subdirectories
BaseDomain string // default request domain for generated client code
QueryEnumAsInt bool // use numeric values for enum query parameters in client code
ServiceGenDir string // per-service handler directory override
NeedModel bool // whether to generate model .go files (false when -use is specified)
HandlerByMethod bool // one handler file per method (vs one per service)
SnakeStyleMiddleware bool // use snake_case naming for middleware functions
SortRouter bool // sort router registration for deterministic output
ForceUpdateClient bool // regenerate hertz_client.go even if it exists
TemplateGenerator
// contains filtered or unexported fields
}
HttpPackageGenerator generates handler, router, model, and client code for one IDL package.
func (*HttpPackageGenerator) GenModel ¶
func (pkgGen *HttpPackageGenerator) GenModel(data *model.Model, gen bool) error
GenModel recursively resolves model file paths and generates Go source files. It first processes all imported models (dependencies), then generates the current model. The gen flag controls whether to actually render the template (false for dependency-only path resolution). processedModels tracks already-visited models to avoid duplicate work.
func (*HttpPackageGenerator) Generate ¶
func (pkgGen *HttpPackageGenerator) Generate(pkg *HttpPackage) error
func (*HttpPackageGenerator) Init ¶
func (pkgGen *HttpPackageGenerator) Init() error
func (*HttpPackageGenerator) LoadBackend ¶
func (pkgGen *HttpPackageGenerator) LoadBackend(backend meta.Backend) error
LoadBackend initializes the model template engine for the given backend. It registers a "ROOT" template function that returns the current model being rendered, allowing templates to access cross-model import information.
type IDLPackageRenderInfo ¶ added in v0.5.1
type IDLPackageRenderInfo struct {
FilePathRenderInfo
ServiceInfos *HttpPackage
}
type Layout ¶
type Layout struct {
OutDir string
GoModule string
ServiceName string
UseApacheThrift bool
HasIdl bool
NeedGoMod bool
ModelDir string
HandlerDir string
RouterDir string
}
Layout contains the basic information of idl
type LayoutGenerator ¶
type LayoutGenerator struct {
ConfigPath string
TemplateGenerator
}
LayoutGenerator contains the information generated by generating the layout template
func (*LayoutGenerator) Degenerate ¶
func (lg *LayoutGenerator) Degenerate() error
func (*LayoutGenerator) Generate ¶
func (lg *LayoutGenerator) Generate(data map[string]interface{}) error
func (*LayoutGenerator) GenerateByConfig ¶
func (lg *LayoutGenerator) GenerateByConfig(configPath string) error
func (*LayoutGenerator) GenerateByService ¶
func (lg *LayoutGenerator) GenerateByService(service Layout) error
func (*LayoutGenerator) Init ¶
func (lg *LayoutGenerator) Init() error
type RegisterInfo ¶ added in v0.6.0
type Router ¶
type Router struct {
FilePath string
PackageName string
HandlerPackages map[string]string // package alias -> import path
Router *RouterNode
}
Router holds the data needed to render the router registration template.
type RouterNode ¶
type RouterNode struct {
GroupName string // parent's middleware var name, used for route registration (e.g. root.GET)
MiddleWare string // this node's middleware var name, becomes GroupName for children
HandlerMiddleware string // middleware name specific to this handler (may differ from GroupMiddleware)
GroupMiddleware string // middleware name for the route group (may use snake_case or camelCase)
PathPrefix string // accumulated path prefix for snake-style middleware naming
Path string
Parent *RouterNode
Children childrenRouterInfo
Handler string // qualified handler call: "pkg.HandlerName"
HandlerPackage string // handler import path
HandlerPackageAlias string // handler import alias
HttpMethod string // HTTP method (GET, POST, etc.) or "" for group-only nodes
}
RouterNode represents a node in the routing tree. The tree structure mirrors the URL path hierarchy. Each node may have:
- Children: sub-path segments forming route groups
- Handler + HttpMethod: a leaf endpoint registration
The tree is used to generate nested router group code with middleware hooks.
func (*RouterNode) DFS ¶
func (routerNode *RouterNode) DFS(i int, hook func(layer int, node *RouterNode) error) error
func (*RouterNode) DyeGroupName ¶
func (routerNode *RouterNode) DyeGroupName(snakeStyleMiddleware bool) error
DyeGroupName traverses the routing tree in depth and names the handler/group middleware for each node. If snakeStyleMiddleware is set to true, the name style of the middleware will use snake name style.
func (*RouterNode) FindNearest ¶
func (routerNode *RouterNode) FindNearest(paths []string, method string, sortRouter bool) (*RouterNode, int)
FindNearest walks the tree to find the deepest node matching the given path segments. Returns the parent node and the index of the first unmatched path segment. When sortRouter is true, it also checks HTTP method to distinguish same-path different-method routes.
func (*RouterNode) Insert ¶
func (routerNode *RouterNode) Insert(name string, method *HttpMethod, handlerType string, paths []string, handlerPkg string, sortRouter bool)
Insert adds child nodes for each remaining path segment. The last segment gets the handler and HTTP method assignment.
func (*RouterNode) RawGroupMiddleware ¶ added in v0.9.8
func (routerNode *RouterNode) RawGroupMiddleware() string
RawGroupMiddleware returns the group middleware base name with path casing preserved. Snake-style middleware already uses the case-preserving full path, so return it without the leading underscore but with any disambiguating suffix.
func (*RouterNode) RawGroupName ¶ added in v0.9.8
func (routerNode *RouterNode) RawGroupName() string
RawGroupName returns the path-derived group name with its original case.
func (*RouterNode) RawHandlerMiddleware ¶ added in v0.9.8
func (routerNode *RouterNode) RawHandlerMiddleware() string
RawHandlerMiddleware returns the handler middleware base name with the handler's original case. It preserves any disambiguating suffix assigned by Hertz without changing HandlerMiddleware itself.
func (*RouterNode) RawHandlerName ¶ added in v0.6.2
func (routerNode *RouterNode) RawHandlerName() string
func (*RouterNode) Sort ¶
func (routerNode *RouterNode) Sort()
func (*RouterNode) Update ¶
func (routerNode *RouterNode) Update(method *HttpMethod, handlerType, handlerPkg string, sortRouter bool) error
Update inserts a new route into the tree. It splits the path into segments, finds the deepest existing node matching the path prefix, then inserts remaining segments as new child nodes.
type Service ¶
type Service struct {
Name string
Methods []*HttpMethod
ClientMethods []*ClientMethod
Models []*model.Model // all dependency models
BaseDomain string // base domain for client code
ServiceGroup string // service level router group
ServiceGenDir string // handler_dir for handler_by_service
}
type SingleHandler ¶ added in v0.8.0
type SingleHandler struct {
*HttpMethod
FilePath string
PackageName string
ProjPackage string
}
type Template ¶
type Template struct {
Default bool // Is it the default template
Path string `yaml:"path"` // The generated path and its filename, such as biz/handler/ping.go
Delims [2]string `yaml:"delims"` // Template Action Instruction Identifier, default: "{{}}"
Body string `yaml:"body"` // Render template, currently only supports go template syntax
Disable bool `yaml:"disable"` // Disable generating file, used to disable default package template
LoopMethod bool `yaml:"loop_method"` // Loop generate files based on "method"
LoopService bool `yaml:"loop_service"` // Loop generate files based on "service"
UpdateBehavior UpdateBehavior `yaml:"update_behavior"` // Update command behavior; 0:unchanged, 1:regenerate, 2:append
}
type TemplateConfig ¶
type TemplateConfig struct {
Layouts []Template `yaml:"layouts"`
}
type TemplateGenerator ¶
type TemplateGenerator struct {
OutputDir string
Config *TemplateConfig
Excludes []string
// contains filtered or unexported fields
}
TemplateGenerator contains information about the output template
func (*TemplateGenerator) Degenerate ¶
func (tg *TemplateGenerator) Degenerate() error
Degenerate removes all files and directories that were created by the template generator. Only removes directories that didn't exist before generation (tracked in tg.dirs).
func (*TemplateGenerator) Files ¶
func (tg *TemplateGenerator) Files() []File
func (*TemplateGenerator) Generate ¶
func (tg *TemplateGenerator) Generate(input interface{}, tplName, filepath string, noRepeat bool) error
Generate renders templates with the given input data and appends results to tg.files. If tplName is specified, only that template is rendered to filepath. If tplName is empty, all loaded templates are rendered (used for layout generation). When input is a map, the "*" key provides global data merged into all templates, and per-template data is keyed by template path.
func (*TemplateGenerator) GetFormatAndExcludedFiles ¶
func (tg *TemplateGenerator) GetFormatAndExcludedFiles() ([]File, error)
func (*TemplateGenerator) Init ¶
func (tg *TemplateGenerator) Init() error
func (*TemplateGenerator) Persist ¶
func (tg *TemplateGenerator) Persist() error
Persist writes all accumulated files to disk, creating directories as needed. Shell scripts (.sh) get executable permissions (0755), other files get 0644.
type UpdateBehavior ¶ added in v0.5.1
type UpdateBehavior struct {
Type string `yaml:"type"` // Update behavior type: skip/cover/append
// the following variables are used for append update
AppendKey string `yaml:"append_key"` // Append content based in key; for example: 'method'/'service'
InsertKey string `yaml:"insert_key"` // Insert content by "insert_key"
AppendTpl string `yaml:"append_content_tpl"` // Append content if UpdateBehavior is "append"
ImportTpl []string `yaml:"import_tpl"` // Import insert template
AppendLocation string `yaml:"append_location"` // AppendLocation specifies the location of append, the default is the end of the file
}