### Example Response with Warnings and Contents Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Plugin.md This example shows how to construct a Response object, including warnings and generated file content. ```go res := &plugin.Response{ Warnings: []string{"unused field detected"}, Contents: []*plugin.FileContent{ {Name: "out.go", Content: "..."}, }, } ``` -------------------------------- ### Install Trimmer via Go Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Install the trimmer tool using the go install command. ```sh go install github.com/cloudwego/thriftgo/tool/trimmer@latest ``` -------------------------------- ### Example Implementation of an External Plugin Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Plugin.md This example demonstrates how to implement the Plugin interface for an external plugin. It logs information from the request and returns a simple generated file. ```go type MyPlugin struct{} func (p *MyPlugin) Name() string { return "my-plugin" } func (p *MyPlugin) Execute(req *plugin.Request) *plugin.Response { fmt.Printf("Generating for %s\n", req.Language) fmt.Printf("AST has %d structs\n", len(req.AST.Structs)) // Generate files... return &plugin.Response{ Contents: []*plugin.FileContent{ {Name: "custom.go", Content: "// custom code", }, }, } } ``` -------------------------------- ### Configure Go Backend Options Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Example of how to pass multiple options to the Go backend using a comma-separated list. This example sets the naming style, enables setter generation, and uses a slim template. ```sh thriftgo -g go:naming_style=golint,gen_setter,template=slim example.thrift ``` -------------------------------- ### GoBackend Generate Method Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Execute the Go code generation pipeline. This example demonstrates setting up a request with AST and generator parameters, calling the Generate method, and handling the response. ```go package main import ( "fmt" "github.com/cloudwego/thriftgo/generator/golang" "github.com/cloudwego/thriftgo/plugin" ) func main() { backend := &golang.GoBackend{} req := &plugin.Request{ Version: "v1.0.0", OutputPath: "./gen", Language: "go", AST: parsedAST, // Assuming parsedAST is defined elsewhere GeneratorParameters: []string{ "naming_style=golint", "gen_setter=true", }, } res := backend.Generate(req, logFunc) // Assuming logFunc is defined elsewhere if res.GetError() != "" { panic(res.GetError()) } // res.Contents now contains generated Go files for _, file := range res.Contents { fmt.Printf("Generated: %s (%d bytes)\n", file.Name, len(file.Content)) } } ``` -------------------------------- ### SDK Plugin Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Plugin.md An example demonstrating how to create an SDK plugin for thriftgo. This plugin generates custom files and is registered using `sdk.RunThriftgoAsSDK`. ```go package main import ( "github.com/cloudwego/thriftgo/plugin" "github.com/cloudwego/thriftgo/sdk" ) type MySDKPlugin struct{} func (p *MySDKPlugin) GetName() string { return "my-sdk-plugin" } func (p *MySDKPlugin) GetPluginParameters() []string { return []string{} } func (p *MySDKPlugin) Invoke(req *plugin.Request) *plugin.Response { // Generate custom files return &plugin.Response{ Contents: []*plugin.FileContent{ { Name: "custom_gen.go", Content: "package main\n\n// custom code", }, }, } } func main() { plugins := []plugin.SDKPlugin{&MySDKPlugin{}} err := sdk.RunThriftgoAsSDK( ".", plugins, "-g", "go", "api.thrift", ) if err != nil { panic(err) } } ``` -------------------------------- ### Install Thriftgo via Go Install Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Use this command to install the latest version of thriftgo directly using Go's package management. ```sh go install github.com/cloudwego/thriftgo@latest ``` -------------------------------- ### Verify Thriftgo Installation Source: https://github.com/cloudwego/thriftgo/blob/main/README.md After installation, run this command to verify that thriftgo is installed correctly and to check its version. ```sh thriftgo --version ``` -------------------------------- ### GoBackend Options Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Iterate through available code generation options for the Go backend. Useful for help systems and validation. ```go backend := new(golang.GoBackend) for _, opt := range backend.Options() { fmt.Printf(" %s: %s\n", opt.Name, opt.Desc) } ``` -------------------------------- ### Thriftgo Default Naming Style Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Demonstrates the default thriftgo naming style, capitalizing words starting with lowercase and leaving uppercase words unchanged. ```Go user_id -> UserId URL -> URL ``` -------------------------------- ### Example IDL Reference Configuration Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Configure IDL path to Go package path mappings for shared types. Place this file in the working directory. ```yaml ref: path/to/shared.thrift: github.com/myorg/shared/gen ``` -------------------------------- ### Golint Naming Style Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Illustrates the golint naming convention which follows standard Go conventions and preserves underscores. ```Go user_id -> UserId http_code -> HTTPCode ``` -------------------------------- ### Trimmer Output Summary Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Example output displayed after running the trimmer tool. ```text removed 42 unused structures with 187 fields success, dump to service_trimmed.thrift ``` -------------------------------- ### Verify Trimmer Installation Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Check the installed version of the trimmer tool. ```sh trimmer --version ``` -------------------------------- ### thriftgo CLI Commands Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Examples of using the thriftgo command-line interface for code generation with different configurations. ```APIDOC ## thriftgo CLI Commands ### Description Examples of using the thriftgo command-line interface for code generation with different configurations. ### Usage Examples ```bash thriftgo -g go service.thrift thriftgo -g go:naming_style=golint,gen_setter service.thrift thriftgo -i ./thrift -r -g go service.thrift ``` ``` -------------------------------- ### Apache Thrift Naming Style Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Shows the Apache Thrift compatibility naming style, which appends underscores to specific names and preserves prefixes. ```Go user_args -> UserArgs_ GetUserResult -> GetUserResult_ ``` -------------------------------- ### Go init() block for Runtime Struct Registration Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Example of an init() block generated by 'gen_type_meta' that registers structs into a global metadata registry for runtime reflection. ```go func init() { meta.RegisterStruct(NewMyStruct, ) } ``` -------------------------------- ### Generate Go Code with Specific Options Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Use the `-g go:` flag to specify options for Go code generation. This example enables golint naming style, generates setters, and uses the slim template. ```bash thriftgo -g go:naming_style=golint,gen_setter,template=slim service.thrift ``` -------------------------------- ### Trimmer Flag Examples Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Common usage examples for various trimmer command-line flags. ```sh trimmer --version ``` ```sh trimmer -h ``` ```sh trimmer -o ./out/service.thrift service.thrift ``` ```sh trimmer -r ./idl -o ./trimmed_idl service.thrift ``` ```sh trimmer -m UserService.GetUser service.thrift ``` ```sh trimmer -p false service.thrift ``` -------------------------------- ### thriftgo SDK Usage Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Examples of invoking thriftgo programmatically using the Go SDK. ```APIDOC ## thriftgo SDK Usage ### Description Examples of invoking thriftgo programmatically using the Go SDK. ### Go SDK Examples ```go import "github.com/cloudwego/thriftgo/sdk" // Invoke thriftgo with specified plugins and arguments sdk.InvokeThriftgo(nil, "thriftgo", "-g", "go", "api.thrift") // Run thriftgo as an SDK with specified working directory and plugins sdk.RunThriftgoAsSDK(".", plugins, "-g", "go", "api.thrift") ``` ``` -------------------------------- ### Create and Use Semantic Checker Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Semantic.md Demonstrates how to create a new semantic checker with options and use it to validate a Thrift AST. This example shows how to handle potential warnings and errors during validation. ```go package main import ( "github.com/cloudwego/thriftgo/semantic" "github.com/cloudwego/thriftgo/parser" ) func main() { ast, _ := parser.ParseFile("api.thrift", nil, false) checker := semantic.NewChecker(semantic.Options{FixWarnings: true}) warns, err := checker.CheckAll(ast) if err != nil { panic(err) } for _, w := range warns { println("Warning:", w) } } ``` -------------------------------- ### Retrieving a Registered Backend Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Generator.md Get a specific backend implementation by its language name. Use this to ensure a backend is available before attempting generation. ```go goBackend := g.GetBackend("go") if goBackend == nil { panic("Go backend not registered") } ``` -------------------------------- ### Dynamically Set Output Path with Namespace Placeholder Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Use the '{namespace}' placeholder in the -o flag to specify output directories based on the Thrift namespace. This example outputs to './gen-go/api/v1/'. ```bash thriftgo -o ./gen-{namespace} -g go api.thrift ``` -------------------------------- ### Example trim_config.yaml Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md This YAML configuration file specifies methods to keep, structs to preserve unconditionally, and paths to included files that should also be preserved. It's automatically picked up by the trimmer if present in the working directory. ```yaml methods: - UserService.GetUser - UserService.CreateUser preserve: true preserved_structs: - CommonError - PageInfo preserved_files: - idl/base/base.thrift ``` -------------------------------- ### Trimmer Tool Usage Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md This section covers the basic usage and installation of the thriftgo trimmer tool. ```APIDOC ## Installation **Prerequisites:** Go 1.18 or later. Ensure `$GOPATH/bin` (default: `~/go/bin`) is in your `PATH`. ```sh go install github.com/cloudwego/thriftgo/tool/trimmer@latest ``` **Build from source:** ```sh git clone https://github.com/cloudwego/thriftgo.git cd thriftgo/tool/trimmer go install ``` **Verify:** ```sh trimmer --version ``` ## Quick start ```sh trimmer service.thrift ``` Produces `service_trimmed.thrift` in the same directory and prints a summary: ``` removed 42 unused structures with 187 fields success, dump to service_trimmed.thrift ``` ## Usage ``` trimmer [options] ``` ``` -------------------------------- ### Perform Semantic Checks and Handle Results Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Semantic.md Illustrates performing all semantic checks on a Thrift AST using Checker.CheckAll and handling both warnings and errors. This example shows how to print warnings and errors or a success message. ```go package main import ( "fmt" "github.com/cloudwego/thriftgo/semantic" "github.com/cloudwego/thriftgo/parser" ) func main() { ast, _ := parser.ParseFile("api.thrift", nil, false) checker := semantic.NewChecker(semantic.Options{}) warns, err := checker.CheckAll(ast) if len(warns) > 0 { fmt.Printf("Warnings: %v\n", warns) } if err != nil { fmt.Printf("Error: %v\n", err) return } println("Validation passed") } ``` -------------------------------- ### Dynamically Set Output Path with NamespaceUnderscore Placeholder Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Use the '{namespaceUnderscore}' placeholder to create output paths where dots in the namespace are replaced by underscores. This example outputs to './generated_api_v1/'. ```bash thriftgo -o ./generated_{namespaceUnderscore} -g go api.thrift ``` -------------------------------- ### Example IDL with Annotations Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/types-enums-constants.md Illustrates how to use annotations within an IDL file to control code generation, such as marking a struct as nested or an alias. ```thrift struct User { 1: required i32 id (thrift.nested = "true"), } (thrift.is_alias = "true") ``` -------------------------------- ### Go Service Interface and Implementations Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Defines a Go interface for a Thrift service and provides example client and server implementations. Includes generated structs for RPC method arguments and results. ```go // Generated type UserService interface { GetUser(ctx context.Context, req *GetUserReq) (*User, error) CreateUser(ctx context.Context, req *CreateUserReq) (*User, error) } type UserServiceClient struct { ... } func (c *UserServiceClient) GetUser(ctx context.Context, req *GetUserReq) (*User, error) { ... } type UserServiceProcessor struct { ... } func (s *UserServiceProcessor) Process(ctx context.Context, iprot, oprot TProtocol) (bool, error) { ... } ``` -------------------------------- ### Generated Go Code for String Literals Source: https://github.com/cloudwego/thriftgo/blob/main/docs/string-literals-in-the-IDL.md Shows the equivalent Go code generated from the Thrift IDL string literal examples, demonstrating how escape sequences and annotations are translated. ```go const ( Str = "'double'\t\\\"quoted\"" Str2 = "\u65b0\u9f99\u6cc9\u5bfa" ) type S struct { F1 string `thrift:"f1,1" json:"hello\tworld" vd:"regexp('^[\\w\u4e00-\u9fa5 _]+$')"` F2 string `thrift:"f2,2" json:"f2"` } func NewS() *S { return &S{ F1: "single'\"quoted", F2: "\u65b0\u9f99\u6cc9\u5bfa", } } ``` -------------------------------- ### Define an SDK Plugin with SDKPlugin Interface Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Plugin.md Implement the SDKPlugin interface for programmatically registered plugins. It includes methods for getting the plugin name, parameters, and invoking the generation logic. ```go type SDKPlugin interface { GetName() string GetPluginParameters() []string Invoke(req *Request) *Response } ``` -------------------------------- ### Run thriftgo as SDK with Working Directory and Plugins Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/SDK.md This function serves as the SDK entry point when running thriftgo as a library. It sets a specific working directory for configuration loading and output generation, and accepts custom SDK plugins and arguments (excluding the tool name). ```go package main import ( "github.com/cloudwego/thriftgo/sdk" "github.com/cloudwego/thriftgo/plugin" ) func main() { plugins := []plugin.SDKPlugin{} err := sdk.RunThriftgoAsSDK( "/myproject", plugins, "-g", "go:naming_style=golint", "api.thrift", ) if err != nil { panic(err) } } ``` -------------------------------- ### Build Trimmer from Source Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Clone the repository and build the trimmer tool locally. ```sh git clone https://github.com/cloudwego/thriftgo.git cd thriftgo/tool/trimmer go install ``` -------------------------------- ### Create SDK Plugin with thriftgo Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Develop a custom SDK plugin by implementing the `plugin.SDKPlugin` interface. Use `sdk.RunThriftgoAsSDK` to execute thriftgo with your plugin. ```go type MyPlugin struct{} func (p *MyPlugin) GetName() string { return "my-plugin" } func (p *MyPlugin) GetPluginParameters() []string { return []string{} } func (p *MyPlugin) Invoke(req *plugin.Request) *plugin.Response { // Generate files... return &plugin.Response{ Contents: []*plugin.FileContent{...}, } } sdk.RunThriftgoAsSDK(".", []plugin.SDKPlugin{&MyPlugin{}}, "-g", "go", "api.thrift") ``` -------------------------------- ### Generate Go code with golint naming and setter methods Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Use this command to generate Go code with specific naming conventions and include setter methods for generated structs. Ensure `example.thrift` is in the current directory. ```sh thriftgo -g go:naming_style=golint,gen_setter example.thrift ``` -------------------------------- ### Trimmer Method Not Found Warning Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Example warning message when a specified method is not found in the IDL. ```text warning: method UserService.NoSuchMethod not found in service.thrift! ``` -------------------------------- ### Go: Typical Thriftgo Compilation Flow Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Semantic.md This Go code demonstrates the typical compilation flow for a Thrift IDL file using thriftgo. It covers parsing, circular include detection, semantic validation, and symbol resolution. Ensure the IDL path is correct and necessary imports are present. ```go package main import ( "fmt" "github.com/cloudwego/thriftgo/parser" "github.com/cloudwego/thriftgo/semantic" ) func compile(idlPath string) error { // 1. Parse ast, err := parser.ParseFile(idlPath, []string{}, true) if err != nil { return err } // 2. Detect circles if path := parser.CircleDetect(ast); len(path) > 0 { return fmt.Errorf("circular include: %s", path) } // 3. Validate semantics checker := semantic.NewChecker(semantic.Options{FixWarnings: true}) warns, err := checker.CheckAll(ast) for _, w := range warns { println("Warning:", w) } if err != nil { return err } // 4. Resolve symbols if err := semantic.ResolveSymbols(ast); err != nil { return err } // 5. Now ready for code generation return nil } ``` -------------------------------- ### Recursive Trimming with -r Flag Source: https://github.com/cloudwego/thriftgo/blob/main/tool/trimmer/README.md Example of using the recursive flag to process included IDL files. ```sh # idl/service.thrift includes idl/base/base.thrift # Output: trimmed_idl/service.thrift, trimmed_idl/base/base.thrift trimmer -r ./idl -o ./trimmed_idl ./idl/service.thrift ``` -------------------------------- ### Define a Thrift struct for FieldMask Source: https://github.com/cloudwego/thriftgo/blob/main/fieldmask/README.md Example Thrift message definition used to demonstrate path navigation. ```thrift struct Example { 1: string Foo, 2: i64 Bar 3: Example Self } ``` -------------------------------- ### Example Trim IDL Warning Source: https://github.com/cloudwego/thriftgo/blob/main/README.md A warning message indicating the number of unused definitions removed during IDL trimming. ```text [WARN] removed 42 unused structures with 187 fields ``` -------------------------------- ### Typical Thriftgo Generation Flow Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Generator.md Demonstrates the standard procedure for generating code using thriftgo. It involves registering a backend, setting up generator arguments including language specifications and request details, executing the generation, and persisting the results. Ensure necessary imports are included. ```go package main import ( "github.com/cloudwego/thriftgo/generator" "github.com/cloudwego/thriftgo/generator/golang" "github.com/cloudwego/thriftgo/plugin" ) func generate(ast *parser.Thrift) error { g := &generator.Generator{} g.RegisterBackend(new(golang.GoBackend)) args := &generator.Arguments{ Out: &generator.LangSpec{ Language: "go", Options: []plugin.Option{ {Name: "naming_style", Desc: "golint"}, {Name: "gen_setter", Desc: "true"}, }, UsedPlugins: []*plugin.Desc{}, SDKPlugins: []plugin.SDKPlugin{}, }, Req: &plugin.Request{ AST: ast, OutputPath: "./generated", Language: "go", Version: "v1.0.0", }, Log: logFunc, } res := g.Generate(args) if res.GetError() != "" { return fmt.Errorf("generation failed: %s", res.GetError()) } if err := g.Persist(res); err != nil { return fmt.Errorf("persist failed: %w", err) } return nil } ``` -------------------------------- ### Get Build FlagSet Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Creates and returns a FlagSet with all thriftgo flags registered. This is used internally by the Parse() method. ```go a.BuildFlags() ``` -------------------------------- ### Generate Fastgo Backend with Slim Template Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Use the 'fastgo' backend to generate Go code with additional fast serialization methods. Specify naming style and template options. Do not combine with '-g go'. ```bash thriftgo -g fastgo:naming_style=golint,template=slim service.thrift ``` -------------------------------- ### Plugin Lookup and Implementation Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Provides mechanisms for discovering and implementing plugins for thriftgo, both external and SDK-based. ```go import "github.com/cloudwego/thriftgo/plugin" // External plugins via binary lookup p, _ := plugin.Lookup("my-plugin") // SDK plugins via interface type MyPlugin struct{} func (p *MyPlugin) GetName() string { ... } func (p *MyPlugin) Invoke(req *plugin.Request) *plugin.Response { ... } ``` -------------------------------- ### Thrift IDL Struct Definition Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Example of a Thrift IDL struct definition that could cause a name collision with generated structs if 'compatible_names' is not used. ```thrift struct GetUserArgs { 1: string id } # would collide with generated GetUser_args ``` -------------------------------- ### Configure IDL Reference Mapping Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Use the 'idl-ref.yaml' format with 'code_ref', 'code_ref_slim', and 'exp_code_ref' options to map IDL file paths to existing Go package paths, avoiding regeneration. ```yaml ref: # IDL file path (relative to working directory): Go package path path/to/shared.thrift: github.com/myorg/shared/gen api/v1/base.thrift: github.com/myorg/api/v1/gen # Packages with types are imported instead of being regenerated ``` -------------------------------- ### Enable Thriftgo Debugging and Profiling Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Set the THRIFTGO_DEBUG environment variable to "1" to enable CPU and heap profiling. This generates .pprof files in the working directory. ```bash export THRIFTGO_DEBUG=1 ``` -------------------------------- ### Generate Go Code with thriftgo CLI Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Use the thriftgo CLI to generate Go code from a Thrift IDL file. Supports various generation options. ```bash thriftgo -g go service.thrift ``` ```bash thriftgo -g go:naming_style=golint,gen_setter service.thrift ``` ```bash thriftgo -i ./thrift -r -g go service.thrift ``` -------------------------------- ### CodeUtils Features Check Example Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Access internal CodeUtils to check for specific feature flags, such as whether setter methods are being generated. This is useful for plugins or post-processing tools. ```go backend := res.(*golang.GoBackend) utils := backend.GetCoreUtils() if utils.Features().GenSetter { // Generate additional setter code } ``` -------------------------------- ### Get Feature Flags from Options Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Retrieves the feature flags determined by the parsed options. Use this to conditionally generate code based on enabled features like GenSetter. ```go func (cu *CodeUtils) Features() *Features ``` ```go utils := newCodeUtils(logFunc) utils.HandleOptions(params) if utils.Features().GenSetter { // Generate Set() methods } ``` -------------------------------- ### Custom Output with Recursive Generation and Plugins Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Configures custom output directory, recursive generation, and applies a plugin with options. ```bash thriftgo -r -o ./generated -g go:naming_style=golint \ -p my-plugin:opt1=val1 \ -v service.thrift ``` -------------------------------- ### Get Identifier Naming Function Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Provides a function to convert Thrift identifiers to Go identifiers based on the configured naming style. Useful for ensuring consistent naming conventions. ```go func (cu *CodeUtils) NamingFunc() func(string) string ``` ```go naming := utils.NamingFunc() goName := naming("user_id") // "UserId" (golint), "UserID", or "UserId" depending on style ``` -------------------------------- ### args Package Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Handles argument parsing for thriftgo, including command-line arguments and plugin specifications. ```APIDOC ## args Package ### Description Handles argument parsing for thriftgo, including command-line arguments and plugin specifications. ### Types - **`Arguments`**: Represents the parsed arguments. ### Methods - **`Parse(args []string)`**: Parses the provided arguments. - **`Targets() ([]string, error)`**: Returns the target files. - **`UsedPlugins() ([]string, error)`**: Returns the used plugins. ### Usage Example ```go import "github.com/cloudwego/thriftgo/args" a := &args.Arguments{} a.Parse(os.Args) specs, _ := a.Targets() plugins, _ := a.UsedPlugins() ``` ``` -------------------------------- ### Get Active Template Name Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Returns the name of the currently active code generation template. This can be "default", "slim", or "raw_struct". ```go func (cu *CodeUtils) Template() string ``` -------------------------------- ### Register Go Backend for Generation Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Instantiate and register the GoBackend with the main generator for Go-specific code generation. ```go import "github.com/cloudwego/thriftgo/generator/golang" backend := &golang.GoBackend{} // Use via generator.Generator.RegisterBackend() ``` -------------------------------- ### Generate Go Code with thriftgo Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Configure and run the code generator for Go. Register the Go backend and specify output options, including naming styles. ```go g := &generator.Generator{} g.RegisterBackend(new(golang.GoBackend)) args := &generator.Arguments{ Out: &generator.LangSpec{ Language: "go", Options: []plugin.Option{{Name: "naming_style", Desc: "golint"}}, }, Req: &plugin.Request{AST: ast, OutputPath: "./gen"}, Log: logFunc, } res := g.Generate(args) if err := g.Persist(res); err != nil { return err } ``` -------------------------------- ### Thrift IDL String Literal Examples Source: https://github.com/cloudwego/thriftgo/blob/main/docs/string-literals-in-the-IDL.md Illustrates various string literal declarations in Thrift IDL, including quoted strings, escaped characters, and Unicode escapes, along with annotations. ```thrift const string str = "'double'\t\"quoted\"" // double quoted const string str2 = "\u65b0\u9f99\u6cc9\u5bfa" struct S { 1: string f1 = 'single\'"quoted' (go.tag = "json:\"hello\tworld\" vd:\"regexp('^[\\w\u4e00-\u9fa5 _]+$')\"") 2: string f2 = "\u65b0\u9f99\u6cc9\u5bfa" } ``` -------------------------------- ### Registering Code Generation Backends Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Generator.md Register different code generation backends like Go and FastGo with the generator. This is typically done during SDK initialization. ```go g := &generator.Generator{} g.RegisterBackend(new(golang.GoBackend)) g.RegisterBackend(new(fastgo.FastGoBackend)) ``` -------------------------------- ### Generate code to a custom output directory with a package prefix Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Specify a custom output directory and a package prefix for the generated Go code. The `-o` flag sets the output directory, and `package_prefix` configures the Go package path. ```sh thriftgo -o ./generated -g go:package_prefix=github.com/myorg/myproject service.thrift ``` -------------------------------- ### Generate Go Code with Golint Naming Style Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Use this command to generate Go code with a specific naming convention applied by the golint style. ```bash thriftgo -g go:naming_style=golint example.thrift ``` -------------------------------- ### Executing the Code Generation Pipeline Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Generator.md Initiates the code generation process for a specified language with given arguments. This method handles backend selection, plugin execution, and collects the generated files. ```go g := &generator.Generator{} g.RegisterBackend(new(golang.GoBackend)) args := &generator.Arguments{ Out: &generator.LangSpec{ Language: "go", Options: []plugin.Option{ {Name: "naming_style", Desc: "golint"}, }, }, Req: &plugin.Request{ AST: parsedAST, // ... }, Log: logFunc, } res := g.Generate(args) if res.GetError() != "" { panic(res.GetError()) } ``` -------------------------------- ### Handle Field Mask Creation Errors Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/FieldMask.md Invalid paths provided to NewFieldMask will result in an error. Ensure all field names exist and type accesses are valid for the struct's fields. This example shows handling an error for a nonexistent field. ```go // Error: struct has no "nonexistent" field mask, err := fieldmask.NewFieldMask( desc, "nonexistent", ) if err != nil { // Handle error } ``` -------------------------------- ### Parse Plugin Specifications Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Parses the -p plugin specifications into plugin descriptions. Handles path separators on Windows by temporarily converting them. ```go a.Plugins = StringSlice{ "my-plugin:key1=val1", "=/path/to/plugin:key2=val2", } descs, err := a.UsedPlugins() if err != nil { log.Fatal(err) } // descs[0].Name = "my-plugin" // descs[0].Options = [{Name: "key1", Desc: "val1"}] ``` -------------------------------- ### GoBackend.BuiltinPlugins Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Indicates that the Go backend does not provide any built-in plugins. ```APIDOC ## BuiltinPlugins ```go func (g *GoBackend) BuiltinPlugins() []*plugin.Desc ``` **Returns:** - `nil` (the Go backend has no built-in plugins). ``` -------------------------------- ### Thriftgo Command-Line Execution Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Architecture.md Use this command to invoke thriftgo. Specify input Thrift files, generation options (like naming style and setter generation), and the output directory. ```bash thriftgo -i ./thrift -g go:naming_style=golint,gen_setter -o ./gen api.thrift ``` -------------------------------- ### GoBackend.GetPlugin Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Attempts to retrieve a plugin based on its description. The Go backend does not provide built-in plugins, so this method always returns nil. ```APIDOC ## GetPlugin ```go func (g *GoBackend) GetPlugin(desc *plugin.Desc) plugin.Plugin ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | desc | `*plugin.Desc` | Plugin description. | **Returns:** - `nil` (the Go backend does not provide built-in plugins). ``` -------------------------------- ### Invoke thriftgo as SDK Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md Programmatically invoke thriftgo using the SDK. Useful for integrating thriftgo into other Go applications. ```go import "github.com/cloudwego/thriftgo/sdk" // For general invocation _ = sdk.InvokeThriftgo(nil, "thriftgo", "-g", "go", "api.thrift") // To run thriftgo as an SDK with plugins _ = sdk.RunThriftgoAsSDK(".", plugins, "-g", "go", "api.thrift") ``` ```go import "github.com/cloudwego/thriftgo/sdk" sdk.InvokeThriftgo(plugins, "thriftgo", "-g", "go", "file.thrift") sdk.RunThriftgoAsSDK(wd, plugins, "-g", "go", "file.thrift") ``` -------------------------------- ### Determine Output Directory Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Returns the output directory for a given language. Applies OutputPath if set, otherwise defaults to './gen-'. ```go a.OutputPath = "./generated/{namespace}" path := a.Output("go") // path = "./generated/{namespace}" ``` -------------------------------- ### Parse Command Line Arguments Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/INDEX.md The args module provides functionality to parse command-line arguments for thriftgo. ```go import "github.com/cloudwego/thriftgo/args" a := &args.Arguments{} a.Parse(os.Args) specs, _ := a.Targets() plugins, _ := a.UsedPlugins() ``` -------------------------------- ### GoBackend.Options Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Retrieves the list of available code generation options for the Go backend. These options are used for validation and help system integration. ```APIDOC ## Options ```go func (g *GoBackend) Options() []plugin.Option ``` **Description:** Returns the list of available code generation options. Used by the help system and for validation. **Returns:** - `[]plugin.Option`: All 50+ supported options with descriptions. See Configuration.md for details. **Example:** ```go backend := new(golang.GoBackend) for _, opt := range backend.Options() { fmt.Printf(" %s: %s\n", opt.Name, opt.Desc) } ``` ``` -------------------------------- ### Minimal Go Code Generation Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Generates Go code with the most basic configuration. ```Bash -g go ``` -------------------------------- ### Generate Code with Plugins and Custom Output Path Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Utilize plugins with custom options and specify a dedicated output directory for generated code. ```bash thriftgo -g go:gen_setter,with_reflection -p my-plugin:opt1=val1 -o ./generated service.thrift ``` -------------------------------- ### HandleOptions Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Parses and validates code generation options provided as a slice of strings. ```APIDOC ## HandleOptions ### Description Parses code generation options (from `GeneratorParameters`) and validates them. This method is typically called during backend initialization. ### Method Signature ```go func (cu *CodeUtils) HandleOptions(params []string) error ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **params** (`[]string`): Options provided in the format `["key1=value1", "key2=value2"]`. ### Returns - `error`: Returns a non-nil error if any option is invalid or incompatible with other selected options. ``` -------------------------------- ### thriftgo Compiler Usage Source: https://github.com/cloudwego/thriftgo/blob/main/README.md The general syntax for using the thriftgo compiler. Specify options and the Thrift IDL file as arguments. ```sh thriftgo [options] ``` -------------------------------- ### Reflection-Enabled Go Generation Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Enables reflection and type metadata generation for dynamic type instantiation. ```bash thriftgo -g go:with_reflection,gen_type_meta service.thrift ``` -------------------------------- ### Production Go Generation with Setters and Deep Equality Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Configuration.md Enables setter methods and deep equality checks for production use cases. ```bash thriftgo -g go:gen_setter,gen_deep_equal service.thrift ``` -------------------------------- ### Generate Go Code from Thrift IDL Source: https://github.com/cloudwego/thriftgo/blob/main/README.md Use this command to generate Go code from a Thrift IDL file. The output will be placed in the './gen-go//' directory. ```sh thriftgo -g go example.thrift ``` -------------------------------- ### Thriftgo Semantic Checker Initialization Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Architecture.md Initializes the semantic checker for validating the Thrift AST. Ensure Options are configured appropriately for your validation needs. ```go semantic.NewChecker(Options{}) ``` -------------------------------- ### Implement String() Method for StringSlice Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Returns a string representation of the StringSlice, typically used for displaying flag help text. ```go func (ss *StringSlice) String() string ``` -------------------------------- ### GoBackend.Generate Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/GoBackend.md Executes the complete code generation process for Go. It parses options, prepares templates, traverses the Abstract Syntax Tree (AST), and generates Go source files. ```APIDOC ## Generate ```go func (g *GoBackend) Generate(req *plugin.Request, log backend.LogFunc) *plugin.Response ``` **Description:** Executes the code generation pipeline. Parses options, prepares templates, walks the AST, generates code, and returns a response containing file contents. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | req | `*plugin.Request` | Compilation request with AST and configuration. | | log | `backend.LogFunc` | Logger for info/warning/error messages. | **Returns:** - `*plugin.Response`: Contains generated file contents, warnings, or an error. **Generation Steps:** 1. Validate and parse options 2. Apply IDL trimming if requested 3. Remove streaming functions if not enabled 4. Prepare Jinja-like templates for code generation 5. Walk the AST and generate code for: - Type definitions (structs, unions, exceptions, enums) - Constants - Serialization methods (`Read`, `Write`) - Client and server stubs - Reflection metadata (if `with_reflection`) - Field-mask support (if `with_field_mask`) - Streaming interfaces (if `thrift_streaming`) 6. Apply post-processing (gofmt) unless `no_fmt` is set 7. Return all generated files **Example:** ```go package main import ( "github.com/cloudwego/thriftgo/generator/golang" "github.com/cloudwego/thriftgo/plugin" ) func main() { backend := &golang.GoBackend{} req := &plugin.Request{ Version: "v1.0.0", OutputPath: "./gen", Language: "go", AST: parsedAST, GeneratorParameters: []string{ "naming_style=golint", "gen_setter=true", }, } res := backend.Generate(req, logFunc) if res.GetError() != "" { panic(res.GetError()) } // res.Contents now contains generated Go files for _, file := range res.Contents { fmt.Printf("Generated: %s (%d bytes)\n", file.Name, len(file.Content)) } } ``` **Source:** `generator/golang/backend.go:87` ``` -------------------------------- ### Parse Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/Arguments.md Parses command-line arguments from argv (typically os.Args). Initializes all fields of the Arguments struct. ```APIDOC ## Parse ### Description Parses command-line arguments from argv (typically `os.Args`). Initializes all fields of the Arguments struct. ### Method `func (a *Arguments) Parse(argv []string) error` ### Parameters #### Path Parameters - **argv** (`[]string`) - Required - Command-line arguments including the program name as the first element (e.g., `[]string{"thriftgo", "-g", "go", "file.thrift"}`). ### Returns - `error`: Non-nil if argument parsing fails (e.g., invalid flag syntax, missing required IDL file). ### Request Example ```go package main import ( "os" "github.com/cloudwego/thriftgo/args" ) func main() { a := &args.Arguments{} err := a.Parse(os.Args) if err != nil { panic(err) } // a.IDL, a.Langs, etc. are now populated } ``` ``` -------------------------------- ### Initialize Fieldmask with TypeDescriptor Source: https://github.com/cloudwego/thriftgo/blob/main/fieldmask/README.md Create a fieldmask instance using the TypeDescriptor of a message and a list of thrift paths. This is typically done during application initialization and the fieldmask can be cached for reuse. ```go import ( "sync" "github.com/cloudwego/thriftgo/fieldmask" nbase "github.com/cloudwego/thriftgo/tests/fieldmask/gen-new/base" ) var fieldmaskCache sync.Map func init() { // new a obj to get its TypeDescriptor obj := nbase.NewBase() desc := obj.GetTypeDescriptor() // construct a fieldmask with TypeDescriptor and thrift pathes fm, err := fieldmask.NewFieldMask(desc, "$.Addr", "$.LogID", "$.TrafficEnv.Code", "$.Meta.IntMap{1}", "$.Meta.StrMap{\"1234\"}", "$.Meta.List[1]", "$.Meta.Set[1]") if err != nil { panic(err) } // cache it for future usage of nbase.Base fieldmaskCache.Store("Mask1ForBase", fm) } ``` -------------------------------- ### Include AST Node Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/types-enums-constants.md Represents an `include` statement in a Thrift file, storing the path and the parsed AST of the included file. ```go type Include struct { Path string // Include path Reference *Thrift // Parsed AST of the included file } ``` -------------------------------- ### Implement Backend Interface for Language Generation Source: https://github.com/cloudwego/thriftgo/blob/main/_autodocs/types-enums-constants.md The Backend interface must be implemented by all language-specific backends. It defines methods for retrieving backend information, generating code, and managing plugins. ```go type Backend interface { Name() string Lang() string Options() []plugin.Option Generate(req *plugin.Request, log backend.LogFunc) *plugin.Response BuiltinPlugins() []*plugin.Desc GetPlugin(desc *plugin.Desc) plugin.Plugin } ```