### Install KeyAuth Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/keyauth.md Install the keyauth extension using go get. ```shell go get github.com/hertz-contrib/keyauth ``` -------------------------------- ### Kitex Profiler Setup Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/advanced-feature/profiler.md Configures and sets up the Kitex profiler with a custom log processor, interval, and window duration. This example demonstrates how to integrate profiler options into server creation. ```go package main import ( "time" "github.com/cloudwego/kitex/pkg/profiler" "github.com/cloudwego/kitex/server" ) // Assume LogProcessor and msgTagging are defined elsewhere // interval, window := time.Duration(0), 30*time.Second // pc := profiler.NewProfiler(LogProcessor, interval, window) // svr := xxxserver.NewServer( // new(ServerImpl), // server.WithProfilerMessageTagging(msgTagging), // server.WithProfiler(pc), // ) ``` -------------------------------- ### Start Server with Combined Service Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/code-gen/combine_service.md Example of how to start a Kitex server using the generated CombineService. This allows all methods from the individual services to be accessible through a single server instance. ```go func main() { svr := api.NewServer(new(combineservice.CombineService)) err := svr.Run() if err != nil { log.Println(err.Error()) } } ``` -------------------------------- ### Complete Custom Protocol Server Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/framework-exten/protocol.md A full example demonstrating the implementation of a custom server, its factory, and its registration with the Hertz engine. This includes handling a simple GET request and responding. ```go package main import ( "bytes" "context" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/cloudwego/hertz/pkg/common/errors" "github.com/cloudwego/hertz/pkg/common/hlog" "github.com/cloudwego/hertz/pkg/network" "github.com/cloudwego/hertz/pkg/protocol" "github.com/cloudwego/hertz/pkg/protocol/suite" ) type myServer struct { suite.Core } func (m myServer) Serve(ctx context.Context, conn network.Conn) error { firstThreeBytes, _ := conn.Peek(3) if !bytes.Equal(firstThreeBytes, []byte("GET")) { return errors.NewPublic("not a GET method") } c := m.GetCtxPool().Get().(*app.RequestContext) defer func() { m.GetCtxPool().Put(c) conn.Skip(conn.Len()) conn.Flush() }() c.Request.SetMethod("GET") c.Request.SetRequestURI("/test") m.ServeHTTP(ctx, c) conn.WriteBinary([]byte("HTTP/1.1 200 OK\n" + "Server: hertz\n" + "Date: Sun, 29 May 2022 10:49:33 GMT\n" + "Content-Type: text/plain; charset=utf-8\n" + "Content-Length: 2\n" + "ok\n")) return nil } type serverFactory struct { } func (s *serverFactory) New(core suite.Core) (server protocol.Server, err error) { return &myServer{ core, }, nil } func main() { h := server.New() h.GET("/test", func(ctx context.Context, c *app.RequestContext) { hlog.Info("in handler") }) h.AddProtocol("http/1.1", &serverFactory{}) h.Spin() } ``` -------------------------------- ### Install Eino and OpenAI Components Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/chain_and_graph_orchestration/chain_graph_introduction.md Installs the necessary Eino and OpenAI component packages using go get. Ensure you have Go installed and configured. ```bash go get github.com/cloudwego/eino-ext/components/model/openai@latest go get github.com/cloudwego/eino@latest ``` -------------------------------- ### Install protoc (Official Image) Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/toolkit/install.md Install the protobuf compiler (protoc) from an official release archive. This example shows steps for macOS, including downloading, unzipping, and copying binaries and include files to standard locations. ```bash wget https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-osx-x86_64.zip unzip protoc-3.19.4-osx-x86_64.zip cp bin/protoc /usr/local/bin/protoc cp -r include/google /usr/local/include/google ``` -------------------------------- ### Callback Handler Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/docs/eino/core_modules/components/agentic_tools_node_guide.md Demonstrates how to create and use a callback handler for tool execution, including handling start, end, and streaming outputs. ```go import ( "context" callbackHelper "github.com/cloudwego/eino/utils/callbacks" "github.com/cloudwego/eino/callbacks" "github.com/cloudwego/eino/compose" "github.com/cloudwego/eino/components/tool" ) // 创建 callback handler handler := &callbackHelper.ToolCallbackHandler{ OnStart: func(ctx context.Context, info *callbacks.RunInfo, input *tool.CallbackInput) context.Context { fmt.Printf("开始执行工具,参数: %s\n", input.ArgumentsInJSON) return ctx }, OnEnd: func(ctx context.Context, info *callbacks.RunInfo, output *tool.CallbackOutput) context.Context { fmt.Printf("工具执行完成,结果: %s\n", output.Response) return ctx }, OnEndWithStreamOutput: func(ctx context.Context, info *callbacks.RunInfo, output *schema.StreamReader[*tool.CallbackOutput]) context.Context { fmt.Println("工具开始流式输出") go func() { defer output.Close() for { chunk, err := output.Recv() if errors.Is(err, io.EOF) { return } if err != nil { return } fmt.Printf("收到流式输出: %s\n", chunk.Response) } }() return ctx }, } // 使用 callback handler helper := callbackHelper.NewHandlerHelper(). Tool(handler). Handler() /*** compose a chain * chain := NewChain * chain.appendxxx(). * appendxxx(). * ... **/ // 在运行时使用 runnable, err := chain.Compile() if err != nil { return err } result, err := runnable.Invoke(ctx, input, compose.WithCallbacks(helper)) ``` -------------------------------- ### Run Kitex Hello Server and Client Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/blog/news/Mastering_Golang_Microservices_A_Practical_Guide_Embrace_High_Performance_with_Kitex_and_Hertz/index.md Instructions for running a basic Kitex 'hello' example server and client using Go commands. ```bash cd kitex-examples/hello go run . go run ./client. ``` -------------------------------- ### Clone Eino Examples Repository Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/devops/visual_debug_plugin_guide.md Clone the eino-examples repository to get started with debugging. Use either HTTPS or SSH URLs. ```bash git clone https://github.com/cloudwego/eino-examples.git # or git clone git@github.com:cloudwego/eino-examples.git ``` -------------------------------- ### Create Local Skill Backend Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/eino_adk/Eino_ADK_ChatModelAgentMiddleware/Middleware_Skill.md This example demonstrates creating a local filesystem backend and then building the Skill middleware using it. Ensure the `skillsDir` variable points to your skills directory. ```go import ( "github.com/cloudwego/eino/adk/middlewares/skill" "github.com/cloudwego/eino-ext/adk/backend/local" ) ctx := context.Background() be, err := local.NewBackend(ctx, &local.Config{}) if err != nil { log.Fatal(err) } skillBackend, err := skill.NewBackendFromFilesystem(ctx, &skill.BackendFromFilesystemConfig{ Backend: be, BaseDir: skillsDir, }) if err != nil { log.Fatalf("Failed to create skill backend: %v", err) } sm, err := skill.NewMiddleware(ctx, &skill.Config{ Backend: skillBackend, }) ``` -------------------------------- ### Install CSRF Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/csrf.md Install the CSRF middleware using go get. ```shell go get github.com/hertz-contrib/csrf ``` -------------------------------- ### Creating a Kitex Client with Options Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/options/client_options.md Demonstrates the basic syntax for creating a new Kitex client and applying custom options. ```go client, err := echo.NewClient("targetService", client.WithXXXX...) ``` -------------------------------- ### Install Polaris Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/docs/hertz/tutorials/third-party/service_discovery/polaris.md Install the Hertz Polaris registry using go get. ```APIDOC ## Install Polaris Registry ```go go get github.com/hertz-contrib/registry/polaris ``` ``` -------------------------------- ### Complete Prompt Implementation Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/components/chat_template_guide.md A comprehensive example demonstrating the implementation of a custom prompt component, including option handling, callback management, and the core formatting logic. ```go type MyPrompt struct { templates []schema.MessagesTemplate formatType schema.FormatType strictMode bool defaultValues map[string]string } func NewMyPrompt(config *MyPromptConfig) (*MyPrompt, error) { return &MyPrompt{ templates: config.Templates, formatType: config.FormatType, strictMode: config.DefaultStrictMode, defaultValues: config.DefaultValues, }, nil } func (p *MyPrompt) Format(ctx context.Context, vs map[string]any, opts ...prompt.Option) ([]*schema.Message, error) { // 1. Handle Options options := &MyPromptOptions{ StrictMode: p.strictMode, DefaultValues: p.defaultValues, } options = prompt.GetImplSpecificOptions(options, opts...) // 2. Get callback manager cm := callbacks.ManagerFromContext(ctx) // 3. Callback before formatting starts ctx = cm.OnStart(ctx, info, &prompt.CallbackInput{ Variables: vs, Templates: p.templates, }) // 4. Execute formatting logic messages, err := p.doFormat(ctx, vs, options) // 5. Handle errors and completion callback if err != nil { ctx = cm.OnError(ctx, info, err) return nil, err } ctx = cm.OnEnd(ctx, info, &prompt.CallbackOutput{ Result: messages, Templates: p.templates, }) return messages, nil } func (p *MyPrompt) doFormat(ctx context.Context, vs map[string]any, opts *MyPromptOptions) ([]*schema.Message, error) { // Implement your own defined logic return messages, nil } ``` -------------------------------- ### Install Eureka Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/eureka.md Install the Eureka registry package using go get. ```go go get github.com/hertz-contrib/registry/eureka ``` -------------------------------- ### Running the Eino Agent Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/overview/bytedance_eino_practice.md Navigate to the eino-examples/eino_assistant directory, source your environment variables, and run the Eino agent Go program. ```bash cd eino-examples/eino_assistant # Load env vars (model info, tracing platform info) source .env # Run from eino_assistant to use the embedded data directory go run cmd/einoagent/*.go ``` -------------------------------- ### Install Hertz Pprof Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/pprof.md Install the pprof middleware using go get. ```shell go get github.com/hertz-contrib/pprof ``` -------------------------------- ### Initialize Hertz Server with Configuration Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/basic-feature/engine.md Demonstrates the basic structure for initializing a Hertz server with configuration options. Use server.WithXXX() methods to apply specific settings. ```go func main() { h := server.New(server.WithXXXX()) ... } ``` -------------------------------- ### Install Hertz i18n Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/i18n.md Use go get to install the hertz-contrib/i18n package. ```go go get github.com/hertz-contrib/i18n ``` -------------------------------- ### Install ServiceComb Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/service-comb.md Install the ServiceComb registry extension for Kitex using go get. ```go go get github.com/kitex-contrib/registry-servicecomb ``` -------------------------------- ### Initialize Hertz Server with Options Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/reference/config.md Demonstrates the basic initialization of a Hertz server using configuration options. Replace WithXXXX with specific configuration functions as needed. ```go package main import "github.com/cloudwego/hertz/pkg/app/server" func main() { hh := server.New(server.WithXXXX()) ... } ``` -------------------------------- ### Install Zookeeper Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/zookeeper.md Install the Zookeeper registry extension for Kitex using go get. ```go go get github.com/kitex-contrib/registry-zookeeper ``` -------------------------------- ### Start Echo Service Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/blog/news/Kitex_kitexcall_practices/index.md Steps to clone the kitex-examples repository and run the basic Echo server locally. ```bash $ git clone https://github.com/cloudwego/kitex-examples.git $ cd kitex-examples/basic/server/ $ go run . [Info] KITEX: server listen at addr=[::]:8888 ``` -------------------------------- ### Navigate to Kitex Example Directory Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Getting started/quick_start.md Change your current directory to the 'hello' folder within the cloned Kitex examples repository. ```bash cd kitex-examples/hello ``` -------------------------------- ### Install Polaris Kitex Extension Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/polaris.md Install the Polaris Kitex extension using go get. ```go go get github.com/kitex-contrib/polaris ``` -------------------------------- ### Server Listening Comparison: Gin vs. Hertz Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/service-migration/_index.md Illustrates how to start a server in Gin using `Run` or `http.Server`, contrasted with Hertz's `Spin` method which requires initialization parameters. ```Go // Gin Run or use http.Server func main() { r := gin.Default() ... r.Run(":8080") // or use http.Server srv := &http.Server{ Addr: ":8080", Handler: r, } } ``` ```Go // Hertz example func main() { r := server.Default(server.WithHostPorts(":8080")) ... r.Spin() } ``` -------------------------------- ### Install Consul Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/consul.md Install the Consul registry extension for Kitex using go get. ```go go get github.com/kitex-contrib/registry-consul ``` -------------------------------- ### Build and Run Kitex Example with Docker Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/blog/news/Mastering_Golang_Microservices_A_Practical_Guide_Embrace_High_Performance_with_Kitex_and_Hertz/index.md Steps to build a Docker image for Kitex examples and run the server and client within Docker containers. ```bash cd kitex-examples docker build -t kitex-examples . docker run --network host kitex-examples ./hello-server docker run --network host kitex-examples ./hello-client ``` -------------------------------- ### Install Eureka Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/eureka.md Install the Eureka registry extension for Kitex using go get. ```go go get github.com/kitex-contrib/registry-eureka ``` -------------------------------- ### Server Example with Eureka Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/docs/kitex/Tutorials/third-party/service_discovery/eureka.md A complete server-side example demonstrating service registration with Eureka. ```go package main import ( "context" "log" "net" "time" "github.com/cloudwego/kitex-examples/hello/kitex_gen/api" "github.com/cloudwego/kitex-examples/hello/kitex_gen/api/hello" "github.com/cloudwego/kitex/pkg/rpcinfo" "github.com/cloudwego/kitex/server" "github.com/kitex-contrib/registry-eureka/registry" ) type HelloImpl struct{} func (h *HelloImpl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) { resp = &api.Response{ Message: req.Message, } return } func main() { r := registry.NewEurekaRegistry([]string{"http://127.0.0.1:8761/eureka"}, 3*time.Second) addr := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 8888} srv := hello.NewServer(new(HelloImpl), server.WithRegistry(r), server.WithServerBasicInfo(&rpcinfo.EndpointBasicInfo{ ServiceName: "Hello", }), server.WithServiceAddr(addr)) err := srv.Run() if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install ZooKeeper Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/zookeeper.md Install the ZooKeeper registry extension for Hertz using go get. ```go go get github.com/hertz-contrib/registry/zookeeper ``` -------------------------------- ### Kitex Server Initialization and Run Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Getting started/tutorial.md This Go code demonstrates the main entry point for a Kitex server. It initializes the server using the service implementation and starts it by calling the `Run` method. ```go package main import ( item "example_shop/kitex_gen/example/shop/item/itemservice" "log" ) func main() { svr := item.NewServer(new(ItemServiceImpl)) err := svr.Run() if err != nil { log.Println(err.Error()) } } ``` -------------------------------- ### Install etcd Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/etcd.md Install the etcd registry extension for Hertz using go get. ```go go get github.com/hertz-contrib/registry/etcd ``` -------------------------------- ### Initialize Kitex Project Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/basic-feature/protocol/streaming/gRPC/thrift_streaming.md Initialize a new Kitex project directory and set up the Go module. This is the first step for new projects using Kitex. ```bash mkdir demo-project && cd demo-project module=demo go mod init $module kitex -module $module -service demo-server api.thrift go mod tidy ``` -------------------------------- ### Install Casbin Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/casbin.md Use go get to install the Casbin middleware package for Hertz. ```shell go get github.com/hertz-contrib/casbin ``` -------------------------------- ### Initialize Apollo Client Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/docs/kitex/Tutorials/third-party/config-center/apollo.md Demonstrates how to initialize the Apollo client with default options. Error handling for initialization is crucial. ```go package main import "github.com/kitex-contrib/config-apollo/apollo" func main() { apolloClient, err := apollo.NewClient(apollo.Options{}) if err!=nil { panic(err) } } ``` -------------------------------- ### Install Secure Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/secure.md Download and install the Secure middleware package using go get. ```shell go get github.com/hertz-contrib/secure ``` -------------------------------- ### Install Hertz Cache Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/cache.md Install the Hertz cache middleware using go get. ```shell go get github.com/hertz-contrib/cache ``` -------------------------------- ### Initialize Hertz Client with Options Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/toolkit/more-feature/client.md Demonstrates how to initialize a generated Hertz client service and apply client-level configurations using `WithHertzClientOption()`. ```go func main() { generatedClient, err := hello_service.NewHelloServiceClient("https://www.example.com"), hello_service.WithHertzClientOption() // Specify client configuration } ``` -------------------------------- ### Install Hertz Gzip Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/gzip.md Install the Hertz Gzip middleware using go get. ```sh go get github.com/hertz-contrib/gzip ``` -------------------------------- ### Initialize Generic HTTP Client with DynamicGo Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/advanced-feature/generic-call/generic-call-dynamicgo.md Demonstrates setting up a Kitex generic HTTP client using DynamicGo. It involves parsing a Thrift IDL file, configuring generic options, and creating the client instance. ```go package main import ( bgeneric "github.com/cloudwego/Kitex/client/genericclient" "github.com/cloudwego/Kitex/pkg/generic" ) func main() { // Local file idl parsing // YOUR_IDL_PATH: thrift file path ex.) ./idl/example.thrift // includeDirs: Specify the include paths, by default the relative path of the current file is used to find the include p, err := generic.NewThriftFileProviderWithDynamicGo("./YOUR_IDL_PATH") if err != nil { panic(err) } // Set generic option for dynamicgo var dopts []generic.Option dopts = append(dopts, generic.UseRawBodyForHTTPResp(true)) // Constructing generic call of http g, err := generic.HTTPThriftGeneric(p, dopts...) if err != nil { panic(err) } cli, err := bgeneric.NewClient("psm", g, opts...) if err != nil { panic(err) } url := "http://example.com/BinaryEcho" body := map[string]interface{}{ "msg": []byte(mockMyMsg), "got_base64": true, "num": "", } data, err := json.Marshal(body) if err != nil { panic(err) } // construct a http request req, err := http.NewRequest(http.MethodGet, url, bytes.NewBuffer(data)) if err != nil { panic(err) } customReq, err := generic.FromHTTPRequest(req) // Considering that the business may use third-party http request, you can construct your own conversion function // customReq *generic.HttpRequest // Since the method for http generic is obtained from the http request via the bam rule, just fill in the blanks resp, err := cli.GenericCall(ctx, "", customReq) realResp := resp.(*generic.HttpResponse) // The body will be stored in RawBody of HTTPResponse as []byte type. // Without using dynamicgo, the body will be stored in Body of HTTPResponse as map[string]interface{} type. node, err := sonic.Get(gr.RawBody, "msg") val, err := node.String() // get the value of "msg" println(val == base64.StdEncoding.EncodeToString([]byte(mockMyMsg))) // true _, ok := gr.Body["msg"] println(ok) // false } ``` -------------------------------- ### Initialize Hertz Client with Options Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/reference/config.md Demonstrates the basic initialization of a Hertz client using functional options. Use `client.WithXxx()` to apply specific configurations. ```go package main import "github.com/cloudwego/hertz/pkg/app/client" func main() { c, err := client.NewClient(client.WithXxx()) ... } ``` -------------------------------- ### Install Access Log Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/access-log.md Install the access log middleware using go get. ```shell go get github.com/hertz-contrib/logger/accesslog ``` -------------------------------- ### Install ETag Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/etag.md Download and install the ETag middleware package using go get. ```shell go get github.com/hertz-contrib/etag ``` -------------------------------- ### Full Example with Casbin Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/casbin.md Demonstrates initializing Hertz server, setting up session storage, creating a Casbin middleware instance with a custom subject lookup handler, and defining routes with permission requirements. ```go package main import ( "context" "log" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/hertz-contrib/casbin" "github.com/hertz-contrib/sessions" "github.com/hertz-contrib/sessions/cookie" ) func main() { h := server.Default() // using sessions to store user info. store := cookie.NewStore([]byte("secret")) h.Use(sessions.New("session", store)) auth, err := casbin.NewCasbinMiddleware("example/config/model.conf", "example/config/policy.csv", subjectFromSession) if err != nil { log.Fatal(err) } h.POST("/login", func(ctx context.Context, c *app.RequestContext) { // verify username and password. // ... // store username (casbin subject) in session session := sessions.Default(c) session.Set("name", "alice") err := session.Save() if err != nil { log.Fatal(err) } c.String(200, "you login successfully") }) h.GET("/book", auth.RequiresPermissions("book:read", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) { c.String(200, "you read the book successfully") }) h.POST("/book", auth.RequiresRoles("user", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) { c.String(200, "you posted a book successfully") }) h.Spin() } // subjectFromSession get subject from session. func subjectFromSession(ctx context.Context, c *app.RequestContext) string { // get subject from session. session := sessions.Default(c) if subject, ok := session.Get("name").(string); !ok { return "" } else { return subject } } ``` -------------------------------- ### Navigate to Kitex Example Repository for Docker Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Getting started/quick_start.md Change your current directory to the root of the cloned Kitex examples repository to prepare for Docker operations. ```bash cd kitex-examples ``` -------------------------------- ### Install Servicecomb Registry Extension Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/servicecomb.md Install the Servicecomb registry extension for Hertz using go get. ```go go get github.com/hertz-contrib/registry/servicecomb ``` -------------------------------- ### Install Hertz Redis Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/redis.md Install the Hertz Redis registry extension using go get. ```go go get github.com/hertz-contrib/registry/redis ``` -------------------------------- ### Custom Server Implementation Example Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/framework-exten/protocol.md Illustrates a basic implementation of a custom server that embeds the Core interface and handles incoming connections. It demonstrates parsing protocol data, invoking business logic via ServeHTTP, and writing data back. ```go type myServer struct{ suite.Core xxx } func (s *myServer) Serve (c context.Context, conn network.Conn) error{ // protocol parsing ... Core.ServeHTTP(c, ctx) // write data back ... } ``` -------------------------------- ### Kitex Client with Apollo Configuration Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/zh/docs/kitex/Tutorials/third-party/config-center/apollo.md Example of setting up a Kitex client with Apollo configuration. Ensure the Apollo client is initialized and service/client names are correctly specified. ```go package main import ( "log" "github.com/cloudwego/kitex-examples/kitex_gen/api/echo" "github.com/cloudwego/kitex/client" "github.com/kitex-contrib/config-apollo/apollo" apolloclient "github.com/kitex-contrib/config-apollo/client" ) func main() { apolloClient, err := apollo.NewClient(apollo.Options{}) if err != nil { panic(err) } serviceName := "ServiceName" // 你的服务端名称 clientName := "ClientName" // 你的客户端名称 client, err := echo.NewClient( serviceName, client.WithHostPorts("0.0.0.0:8888"), client.WithSuite(apolloclient.NewSuite(serviceName, clientName, apolloClient)), ) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install Polaris Registry for Hertz Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/polaris.md Install the Polaris registry extension for Hertz using go get. ```go go get github.com/hertz-contrib/registry/polaris ``` -------------------------------- ### Install Hertz Consul Registry Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/service_discovery/consul.md Install the Hertz Consul registry extension using go get. ```go go get github.com/hertz-contrib/registry/consul ``` -------------------------------- ### Install Hertz Request ID Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/requestid.md Download and install the requestid package using go get. ```shell go get github.com/hertz-contrib/requestid ``` -------------------------------- ### Create Server with Options Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/options/server_options.md Add options when creating a new Kitex server instance. ```go svr := api.NewServer(new(DemoImpl), server.WithXXX...) ``` -------------------------------- ### File Loader Example with Parser Configuration Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/components/document_loader_guide/document_parser_interface_guide.md Demonstrates initializing a FileLoader with a TextParser and loading a document from a file. It logs the document content and extracted metadata like extension and source. ```go import ( "github.com/cloudwego/eino/components/document" "github.com/cloudwego/eino/schema" "github.com/cloudwego/eino-ext/components/document/loader/file" ) ctx := context.Background() loader, err := file.NewFileLoader(ctx, &file.FileLoaderConfig{ UseNameAsID: true, Parser: &parser.TextParser{}, // Or parser.NewExtParser() }) filePath := "../../testdata/test.md" docs, err := loader.Load(ctx, document.Source{ URI: filePath }) log.Printf("doc content: %v", docs[0].Content) log.Printf("Extension: %s\n", docs[0].MetaData[file._MetaKeyExtension_]) log.Printf("Source: %s\n", docs[0].MetaData[file._MetaKeySource_]) ``` -------------------------------- ### Install Hertz CORS Middleware Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/hertz/tutorials/third-party/middleware/cors.md Install the Hertz CORS middleware using the go get command. ```shell go get github.com/hertz-contrib/cors ``` -------------------------------- ### Install Nacos SDK (v2) Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/nacos.md Install the Nacos SDK for Go version 2 using go get. ```go go get github.com/kitex-contrib/registry-nacos/v2 ``` -------------------------------- ### Build Kitex Docker Image Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Getting started/quick_start.md Build a Docker image tagged as 'kitex-examples' from the current directory, which contains the Kitex example code. ```bash docker build -t kitex-examples . ``` -------------------------------- ### Install Nacos SDK (v1) Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/kitex/Tutorials/third-party/service_discovery/nacos.md Install the Nacos SDK for Go version 1 using go get. ```go go get github.com/kitex-contrib/registry-nacos ``` -------------------------------- ### Basic Local Backend Usage: Write and Read Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/eino_adk/Eino_ADK_ChatModelAgentMiddleware/filesystem_backend/backend_本地文件系统.md Demonstrates the basic usage of the local backend by writing content to a file and then reading it back. Ensure file paths are absolute. ```go import ( "context" "github.com/cloudwego/eino-ext/adk/backend/local" "github.com/cloudwego/eino/adk/filesystem" ) func main() { ctx := context.Background() backend, err := local.NewBackend(ctx, &local.Config{}) if err != nil { panic(err) } // Write file (must be absolute path) err = backend.Write(ctx, &filesystem.WriteRequest{ FilePath: "/tmp/hello.txt", Content: "Hello, Local Backend!", }) // Read file fcontent, err := backend.Read(ctx, &filesystem.ReadRequest{ FilePath: "/tmp/hello.txt", }) fmt.Println(fcontent.Content) } ``` -------------------------------- ### Install Local Backend Package Source: https://github.com/cloudwego/cloudwego.github.io/blob/main/content/en/docs/eino/core_modules/eino_adk/Eino_ADK_ChatModelAgentMiddleware/filesystem_backend/backend_本地文件系统.md Use 'go get' to install the local backend package for your Eino project. ```bash go get github.com/cloudwego/eino-ext/adk/backend/local ```