### Quick Start MCP Server Example Source: https://github.com/go-kratos/kratos/blob/main/contrib/transport/mcp/README.md Demonstrates how to initialize and run an MCP server with a custom tool handler and middleware. Ensure necessary imports are included. ```go import( tm "github.com/go-kratos/kratos/contrib/transport/mcp/v3" mcp "github.com/mark3labs/mcp-go/mcp" ) func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { name, ok := request.Params.Arguments["name"].(string) if !ok { return nil, errors.New("name must be a string") } return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil } func Health(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/health/ready" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } func main() { srv := tm.NewServer("kratos-mcp", "v1.0.0", tm.Address(":8000"), tm.Middleware(Health)) tool := mcp.NewTool("hello_world", mcp.WithDescription("Say hello to someone"), mcp.WithString("name", mcp.Required(), mcp.Description("Name of the person to greet"), ), ) // Add tool handler srv.AddTool(tool, helloHandler) // creates a kratos application app := kratos.New( kratos.Name("kratos-app"), kratos.Server(srv), ) if err := app.Run(); err != nil { panic(err) } } ``` -------------------------------- ### Install Go on Windows Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Download the Go installer for Windows. Set environment variables. ```shell 下载:https://dl.google.com/go/go1.12.4.windows-amd64.msi 添加环境变量: set GO111MODULE=on set GOPATH=D:\gopath ``` -------------------------------- ### Install Kratos CLI Source: https://github.com/go-kratos/kratos/blob/main/README.md Installs the Kratos command-line interface. Ensure Go 1.25+ is installed. ```shell go install github.com/go-kratos/kratos/cmd/kratos/v3@latest kratos upgrade ``` -------------------------------- ### Install Go on Linux Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Download and install Go on Linux. Configure environment variables in .bashrc. ```shell wget https://dl.google.com/go/go1.12.4.linux-amd64.tar.gz sudo tar -xzf go1.12.4.linux-amd64.tar.gz -C /usr/local vim ~/.bashrc export GO111MODULE=on export GOROOT=/usr/local/go export GOPATH=~/gopath export PATH=$PATH:$GOPATH/bin export PATH=$PATH:$GOROOT/bin ``` -------------------------------- ### Install Protobuf Compiler on Ubuntu/Debian Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Use snap to install the protobuf compiler on Ubuntu or Debian. ```shell sudo snap install --classic protobuf ``` -------------------------------- ### Install Kubernetes Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Kubernetes registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/kubernetes/v3 ``` -------------------------------- ### Install Swagger Docs Tool Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Install the go-swagger command-line tool. Use it to serve Swagger JSON files. ```shell go get github.com/go-swagger/go-swagger/tree/master/cmd/swagger swagger serve api/api.swager.json ``` -------------------------------- ### Install Protobuf Compiler on Mac Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Use Homebrew to install the protobuf compiler on macOS. ```shell brew install protobuf ``` -------------------------------- ### Install Go Protobuf Generator Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Install the gogofast protobuf generator for Go. Use it to generate code from .proto files. ```shell go get github.com/gogo/protobuf/protoc-gen-gogofast kratos tool protoc api.proto ``` -------------------------------- ### Install Protobuf Compiler on Windows Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Download the protobuf compiler for Windows. Add its bin directory to the system PATH. ```shell 下载:https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/protoc-3.7.1-win64.zip 解压文件到:C:\protobuf 添加环境变量: set PATH=%PATH%;C:\protobuf\bin ``` -------------------------------- ### Install Go on macOS Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Use Homebrew to install Go on macOS. Configure environment variables in .bashrc. ```shell brew install go vim ~/.bashrc export GO111MODULE=on export GOPATH=~/gopath ``` -------------------------------- ### Install Consul Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Consul registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/consul/v3 ``` -------------------------------- ### Install Protobuf Compiler on Linux Source: https://github.com/go-kratos/kratos/wiki/Kratos-Requirements Download and install the protobuf compiler on Linux. Configure environment variables in .bashrc. ```shell wget https://github.com/google/protobuf/releases/download/v3.7.1/protoc-3.7.1-linux-x86_64.zip sudo tar -xzf go1.12.4.linux-amd64.tar.gz -C ~/.protobuf vim ~/.bashrc export PROTOBUF=~/.protobuf export PATH=$PATH:$PROTOBUF/bin ``` -------------------------------- ### Install Etcd Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Etcd registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/etcd/v3 ``` -------------------------------- ### Install Kubernetes Config for Kratos Source: https://github.com/go-kratos/kratos/blob/main/config/README.md Use this command to install the Kubernetes configuration client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/config/kubernetes/v3 ``` -------------------------------- ### Install Zookeeper Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Zookeeper registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/zookeeper/v3 ``` -------------------------------- ### Install Polaris Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Polaris registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/polaris/v3 ``` -------------------------------- ### Install Nacos Registry Client Source: https://github.com/go-kratos/kratos/blob/main/registry/README.md Use this command to install the Nacos registry client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/registry/nacos/v3 ``` -------------------------------- ### Install etcd Config for Kratos Source: https://github.com/go-kratos/kratos/blob/main/config/README.md Use this command to install the etcd configuration client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/config/etcd/v3 ``` -------------------------------- ### Install Apollo Config for Kratos Source: https://github.com/go-kratos/kratos/blob/main/config/README.md Use this command to install the Apollo configuration client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/config/apollo/v3 ``` -------------------------------- ### Create and Run a New Kratos Service Source: https://github.com/go-kratos/kratos/blob/main/README.md Generates a new Kratos service, navigates into its directory, tidies dependencies, and runs the service. Visit http://localhost:8000/helloworld/kratos after it starts. ```shell kratos new helloworld cd helloworld go mod tidy kratos run ``` -------------------------------- ### Initialize OTel Logger with Custom Filters Source: https://github.com/go-kratos/kratos/blob/main/contrib/otel/README.md When the logger requires fixed attributes or filtering, use the core Kratos log builder. This example shows how to add a filter for 'password' and set a service name. ```go import ( "log/slog" otel "github.com/go-kratos/kratos/contrib/otel/v3/log" "github.com/go-kratos/kratos/v3/log" ) logger := log.NewLogger( otel.NewHandler("helloworld"), log.WithFilter(log.FilterKey("password")), ).With(slog.String("service.name", "helloworld")) ``` -------------------------------- ### Apollo Configuration Structure Example Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/apollo/README.md Illustrates how configuration loaded from an Apollo namespace, like `application.json`, is structured within the Kratos config instance. The namespace becomes part of the key path. ```json { "http": { "address": ":8080", "tls": { "enable": false, "cert_file": "", "key_file": "" } } } ``` -------------------------------- ### Install Nacos Config for Kratos Source: https://github.com/go-kratos/kratos/blob/main/config/README.md Use this command to install the Nacos configuration client for Kratos. ```shell go get -u github.com/go-kratos/kratos/contrib/config/nacos/v3 ``` -------------------------------- ### Discover Service with Nacos Client Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/nacos/README.md Configure a Go-Kratos client to discover services registered in Nacos. This example uses gRPC for communication. ```go package main import ( "context" "log" "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" "github.com/go-kratos/kratos/contrib/registry/nacos/v3" "github.com/go-kratos/kratos/v3/transport/grpc" ) func main() { cc := constant.ClientConfig{ NamespaceId: "public", TimeoutMs: 5000, } client, err := clients.NewNamingClient( vo.NacosClientParam{ ClientConfig: &cc, }, ) if err != nil { log.Panic(err) } r := nacos.New(client) // client conn, err := grpc.NewClient( context.Background(), grpc.WithEndpoint("discovery:///helloworld"), grpc.WithDiscovery(r), ) defer conn.Close() } ``` -------------------------------- ### ServiceComb Server Registration Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/servicecomb/README.md Example of a Kratos server registering with the ServiceComb registry. Ensure the ServiceComb client is initialized with the correct endpoints. ```go package main import ( "log" "github.com/go-chassis/sc-client" "github.com/go-kratos/kratos/contrib/registry/servicecomb/v3" "github.com/go-kratos/kratos/v3" ) func main() { c, err := sc.NewClient(sc.Options{ Endpoints: []string{"127.0.0.1:30100"}, }) if err != nil { log.Panic(err) } r := servicecomb.NewRegistry(c) app := kratos.New( kratos.Name("helloServicecomb"), kratos.Registrar(r), ) if err := app.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Conventional Commits - Full Commit Message Example Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md A comprehensive example of a commit message including type, scope, breaking change, body, and footer for issue referencing. ```text fix(log): [BREAKING-CHANGE] unable to meet the requirement of log Library Explain the reason, purpose, realization method, etc. Close #777 Doc change on doc/#111 BREAKING CHANGE: Breaks log.info api, log.log should be used instead ``` -------------------------------- ### Conventional Commits - Simple Commit Message Example Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md A basic example of a commit message using the 'fix' type and a description. ```text fix: The log debug level should be -1 ``` -------------------------------- ### ServiceComb Client Discovery Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/servicecomb/README.md Example of a Kratos client discovering a service registered with ServiceComb. It uses gRPC with discovery enabled, pointing to the service name. ```go package main import ( "context" "log" "github.com/go-chassis/sc-client" "github.com/go-kratos/kratos/contrib/registry/servicecomb/v3" "github.com/go-kratos/kratos/v3/transport/grpc" ) func main() { c, err := sc.NewClient(sc.Options{ Endpoints: []string{"127.0.0.1:30100"}, }) if err != nil { log.Panic(err) } r := servicecomb.NewRegistry(c) ctx := context.Background() conn, err := grpc.NewClient( ctx, grpc.WithEndpoint("discovery:///helloServicecomb"), grpc.WithDiscovery(r), ) if err != nil { return } defer conn.Close() } ``` -------------------------------- ### Refresh Dependencies Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md After updating module paths, refresh your project's dependencies using `go get` and `go mod tidy`. ```shell go get github.com/go-kratos/kratos/v3@latest go mod tidy ``` -------------------------------- ### Conventional Commits - Type Examples Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md Use these types to categorize your commits. 'fix' and 'feat' are for bug fixes and new features respectively. ```text - **fix**: A bug fix - **feat**: A new feature - **deps**: Changes external dependencies - **break**: Changes has break change - **docs**: Documentation only changes - **refactor**: A code change that neither fixes a bug nor adds a feature - **style**: Changes that do not affect the meaning of the code (white-space, formatting, etc) - **test**: Adding missing tests or correcting existing tests - **chore** Daily work, examples, etc. - **ci**: Changes to our CI configuration files and scripts ``` -------------------------------- ### Conventional Commits - Scope Examples Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md Scopes indicate the part of the codebase affected by the commit. Use relevant scopes like 'transport' or 'middleware'. ```text - transport - examples - middleware - config - cmd - etc. ``` -------------------------------- ### Conventional Commits - Commit Message with Scope and Breaking Change Indicator Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md This example shows a commit message with a scope and a breaking change indicator (!). ```text refactor!(transport/http): replacement underlying implementation ``` -------------------------------- ### Update JWT Dependencies Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md After changing the JWT middleware import path, run `go get` for the new path and `go mod tidy` to update your project's dependencies. ```shell go get github.com/go-kratos/kratos/contrib/middleware/jwt/v3@latest go mod tidy ``` -------------------------------- ### Initialize and Report Metadata with OpenSergo Source: https://github.com/go-kratos/kratos/blob/main/contrib/opensergo/README.md Demonstrates initializing OpenSergo with a specified endpoint and reporting application metadata. Ensure OpenSergo is configured with the correct endpoint. ```go osServer, err := opensergo.New(opensergo.WithEndpoint("localhost:9090")) if err != nil { panic("init opensergo error") } s := &server{} grpcSrv := grpc.NewServer( grpc.Address(":9000"), grpc.Middleware( recovery.Recovery(), ), ) helloworld.RegisterGreeterServer(grpcSrv, s) app := kratos.New( kratos.Name(Name), kratos.Server( grpcSrv, ), ) osServer.ReportMetadata(context.Background(), app) if err := app.Run(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Serve Swagger API Documentation Source: https://github.com/go-kratos/kratos/wiki/Kratos-Tools:-kratos-swagger Use this command to serve your API's Swagger documentation. After execution, the Swagger UI will automatically open in your browser. Refer to go-swagger documentation for additional parameters. ```shell kratos tool swagger serve api/api.swagger.json ``` -------------------------------- ### Configure Etcd as a Kratos Config Source Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/etcd/README.md Demonstrates creating an Etcd client, configuring the Kratos config source with a path and prefix, and loading configuration values. ```go import ( "log" "time" clientv3 "go.etcd.io/etcd/client/v3" cfg "github.com/go-kratos/kratos/contrib/config/etcd/v3" "github.com/go-kratos/kratos/v3/config" ) // create an etcd client client, err := clientv3.New(clientv3.Config{ Endpoints: []string{"127.0.0.1:2379"}, DialTimeout: time.Second, }) if err != nil { log.Fatal(err) } // configure the source, "path" is required source, err := cfg.New(client, cfg.WithPath("/app-config"), cfg.WithPrefix(true)) if err != nil { log.Fatalln(err) } // create a config instance with source c := config.New(config.WithSource(source)) deferr c.Close() // load sources before get if err := c.Load(); err != nil { log.Fatalln(err) } // acquire config value foo, err := c.Value("/app-config").String() if err != nil { log.Fatalln(err) } log.Println(foo) ``` -------------------------------- ### Basic Kratos Service Initialization Source: https://github.com/go-kratos/kratos/blob/main/README.md Initializes a Kratos application with a name, version, and registers HTTP and gRPC servers. Ensure necessary imports are present. ```go package main import ( "github.com/go-kratos/kratos/v3" "github.com/go-kratos/kratos/v3/transport/grpc" "github.com/go-kratos/kratos/v3/transport/http" ) func main() { httpSrv := http.NewServer(http.Address(":8000")) grpcSrv := grpc.NewServer(grpc.Address(":9000")) app := kratos.New( kratos.Name("helloworld"), kratos.Version("v1.0.0"), kratos.Server(httpSrv, grpcSrv), ) if err := app.Run(); err != nil { panic(err) } } ``` -------------------------------- ### Initialize Consul Configuration Source Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/consul/README.md Demonstrates how to initialize the Consul configuration source in Kratos. Ensure the Consul client is correctly configured and the path to your configuration files in Consul is specified. ```go import ( "github.com/hashicorp/consul/api" "github.com/go-kratos/kratos/contrib/config/consul/v3" ) func main() { consulClient, err := api.NewClient(&api.Config{ Address: "127.0.0.1:8500", }) if err != nil { panic(err) } cs, err := consul.New(consulClient, consul.WithPath("app/cart/configs/")) // consul中需要标注文件后缀,kratos读取配置需要适配文件后缀 // The file suffix needs to be marked, and kratos needs to adapt the file suffix to read the configuration. if err != nil { panic(err) } c := config.New(config.WithSource(cs)) } ``` -------------------------------- ### Initialize Polaris Config API and Load Configuration Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/polaris/README.md Demonstrates how to initialize the Polaris Config API and load configuration from a specified namespace, file group, and file name. Ensure Polaris client is properly configured before use. ```go import ( "log" "github.com/polarismesh/polaris-go" "github.com/go-kratos/kratos/contrib/config/polaris/v3" ) func main() { configApi, err := polaris.NewConfigAPI() if err != nil { log.Fatalln(err) } source, err := polaris.New(&configApi, polaris.WithNamespace("default"), polaris.WithFileGroup("default"), polaris.WithFileName("default.yaml")) if err != nil { log.Fatalln(err) } source.Load() } ``` -------------------------------- ### Register a Service with Discovery Registry Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/discovery/README.md Initializes a discovery registry and registers a Kratos application with it. Ensure the discovery nodes are correctly configured. ```go import ( "github.com/go-kratos/kratos/contrib/registry/discovery/v3" ) func main() { // initialize a registry r := discovery.New(&discovery.Config{ Nodes: []string{"0.0.0.0:7171"}, Env: "dev", Region: "sh1", Zone: "zone1", Host: "hostname", }) // construct srv instance // ... app := kratos.New( kratos.Name("helloworld"), kratos.Server( httpSrv, grpcSrv, ), kratos.Metadata(map[string]string{"color": "gray"}), // use Registrar kratos.Registrar(r), ) if err := app.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Initialize Sentry Client Source: https://github.com/go-kratos/kratos/blob/main/contrib/errortracker/sentry/README.md Initialize the Sentry client in your application's entry point. Ensure to provide your DSN and consider enabling AttachStacktrace for better debugging. ```go import "github.com/getsentry/sentry-go" sentry.Init(sentry.ClientOptions{ Dsn: "", AttachStacktrace: true, // recommended }) ``` -------------------------------- ### Initialize OTel Logger Handler Source: https://github.com/go-kratos/kratos/blob/main/contrib/otel/README.md Use this to create a new OpenTelemetry logger handler for Kratos. Ensure the otel package is imported as 'otel'. ```go import ( otel "github.com/go-kratos/kratos/contrib/otel/v3/log" "github.com/go-kratos/kratos/v3/log" ) logger := log.NewLogger(otel.NewHandler("helloworld")) ``` -------------------------------- ### Configure Kratos Application Logger Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md Kratos v3 application and middleware options now accept `*slog.Logger`. Pass the configured logger to `kratos.New` using the `kratos.Logger` option. ```go app := kratos.New( kratos.Name("helloworld"), kratos.Logger(logger), ) ``` -------------------------------- ### Initialize Apollo Config Source in Kratos Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/apollo/README.md Use this snippet to set up the Apollo configuration source for your Kratos application. It demonstrates how to configure essential parameters like AppID, Cluster, Endpoint, and Namespaces. ```go import ( "fmt" "log" "github.com/go-kratos/kratos/contrib/config/apollo/v3" "github.com/go-kratos/kratos/v3/config" ) func main() { c := config.New( config.WithSource( apollo.NewSource( apollo.WithAppID("kratos"), apollo.WithCluster("dev"), apollo.WithEndpoint("http://localhost:8080"), apollo.WithNamespace("application,event.yaml,demo.json"), apollo.WithEnableBackup(), apollo.WithSecret("ad75b33c77ae4b9c9626d969c44f41ee"), ), ), ) var bc bootstrap if err := c.Load(); err != nil { panic(err) } // use value and watch operations,help yourself. } ``` -------------------------------- ### Discover a Service using Discovery Registry Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/discovery/README.md Initializes a discovery client and configures a gRPC client to use it for service discovery. The endpoint format `discovery:///appid` is used to specify the target service. ```go import ( "github.com/go-kratos/kratos/contrib/registry/discovery/v3" "github.com/go-kratos/kratos/v3/transport/grpc" ) func main() { // initialize a discovery r := discovery.New(&discovery.Config{ Nodes: []string{"0.0.0.0:7171"}, Env: "dev", Region: "sh1", Zone: "zone1", Host: "localhost", }, nil) conn, err := grpc.NewClient( context.Background(), grpc.WithEndpoint("discovery:///appid"), // use discovery grpc.WithDiscovery(r), ) if err != nil { log.Fatal(err) } defer conn.Close() // request and log } ``` -------------------------------- ### Build Custom Logger with Kratos Decorators Source: https://github.com/go-kratos/kratos/blob/main/log/README.md Builds a default handler and wraps it with Kratos decorators using `log.NewLogger`. Attach fixed service attributes with `logger.With`. Use `log.WithFilter` to redact sensitive keys. ```go logger := log.NewLogger( slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, }), log.WithFilter(log.FilterKey("password")), // redact sensitive keys ).With( slog.String("service.id", id), slog.String("service.name", name), slog.String("service.version", version), ) log.SetDefault(logger) ``` -------------------------------- ### Initialize Nacos Config Client Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/nacos/README.md Initializes the Nacos configuration client with server and client configurations. Ensure Nacos server is running and accessible. ```go import ( "github.com/nacos-group/nacos-sdk-go/clients" "github.com/nacos-group/nacos-sdk-go/common/constant" kconfig "github.com/go-kratos/kratos/v3/config" ) sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848), } cc := &constant.ClientConfig{ NamespaceId: "public", //namespace id TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: "/tmp/nacos/log", CacheDir: "/tmp/nacos/cache", LogLevel: "debug", } // a more graceful way to create naming client client, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: cc, ServerConfigs: sc, }, ) if err != nil { log.Panic(err) } ``` -------------------------------- ### Use OpenTelemetry Logging Handler Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md For OpenTelemetry integration, use the provided contrib handler. Initialize the logger with `otel.NewHandler`. ```go import ( "github.com/go-kratos/kratos/v3/log" otel "github.com/go-kratos/kratos/contrib/otel/v3/log" ) logger := log.NewLogger(otel.NewHandler("helloworld")) ``` -------------------------------- ### Apollo Config Options Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/apollo/README.md This section lists available options for configuring the Apollo source. Each option corresponds to a specific setting for connecting to and managing configurations from Apollo. ```go // specify the app id func WithAppID(appID string) Option // specify the cluster of application func WithCluster(cluster string) Option // enable backup or not, and where to back up them. func WithBackupPath(backupPath string) Option func WithDisableBackup() Option func WithEnableBackup() Option // specify apollo endpoint, such as http://localhost:8080 func WithEndpoint(endpoint string) Option // namespaces to load, comma to separate. func WithNamespace(name string) Option // secret is the apollo secret key to access application config. func WithSecret(secret string) Option ``` -------------------------------- ### Validate Kratos Upgrade with Tests and Linters Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md Run project tests and linters to validate the upgrade before shipping. For this repository, use `make test` and `make lint`. ```shell go test ./... go vet ./... ``` ```shell make test make lint ``` -------------------------------- ### Run Kratos Tests and Lint Source: https://github.com/go-kratos/kratos/blob/main/README.md Executes the test suite and lints the project code using make commands. ```shell make test make lint ``` -------------------------------- ### Generate Service Code with Kratos Source: https://github.com/go-kratos/kratos/blob/main/README.md Adds a proto file, generates client and server code, and runs the Kratos application. This is for a fuller generated service flow. ```shell kratos proto add api/helloworld/helloworld.proto kratos proto client api/helloworld/helloworld.proto kratos proto server api/helloworld/helloworld.proto -t internal/service go generate ./... kratos run ``` -------------------------------- ### Replace Direct HTTP Binding Imports Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md Replace `binding.EncodeURL` with `http.BuildPath` and use `transport/http.Context` methods for binding. Use `encoding/form` directly only for low-level needs. ```go path := http.BuildPath("/v1/users/{id}", req) ``` -------------------------------- ### Use Contrib JSON Codec for v2 Compatibility Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md If your service relies on the v2 behavior where the `json` codec handled both standard JSON and protobuf messages, use the `contrib/encoding/json/v3` compatibility codec during migration. ```go import _ "github.com/go-kratos/kratos/contrib/encoding/json/v3" ``` -------------------------------- ### Explicitly Import Standard and ProtoJSON Codecs Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md For new v3 code, explicitly import the standard `json` and `protojson` codecs. This ensures clear separation of concerns for JSON handling. ```go import ( _ "github.com/go-kratos/kratos/v3/encoding/json" _ "github.com/go-kratos/kratos/v3/encoding/protojson" ) ``` -------------------------------- ### Kratos Config Instance Structure from Apollo Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/apollo/README.md Shows the resulting structure of configuration data within a Kratos config instance when loaded from an Apollo namespace such as `application.json`. Note how the namespace is incorporated into the key hierarchy. ```go config := map[string]interface{}{ // application be part of the key path. "application": map[string]interface{}{ "http": map[string]interface{}{ "address": ":8080", "tls": map[string]interface{}{ "enable": false, "cert_file": "", "key_file": "", }, }, }, } ``` -------------------------------- ### Register Server with Nacos Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/nacos/README.md Configure and run a Go-Kratos server that registers itself with Nacos. Ensure Nacos is running and accessible. ```go package main import ( "log" "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" "github.com/go-kratos/kratos/contrib/registry/nacos/v3" "github.com/go-kratos/kratos/v3" ) func main() { sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848), } client, err := clients.NewNamingClient( vo.NacosClientParam{ ServerConfigs: sc, }, ) if err != nil { log.Panic(err) } r := nacos.New(client) // server app := kratos.New( kratos.Name("helloworld"), kratos.Registrar(r), ) if err := app.Run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Configure Kratos with KubeConfig Outside Cluster Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/kubernetes/README.md Initialize a Kratos configuration source using a local KubeConfig file for usage outside the Kubernetes cluster. Ensure the KubeConfig path is correctly set. ```go config.NewSource(SourceOption{ Namespace: "mesh", LabelSelector: "", KubeConfig: filepath.Join(homedir.HomeDir(), ".kube", "config"), }) ``` -------------------------------- ### Configure HTTP Server with Sentry Middleware Source: https://github.com/go-kratos/kratos/blob/main/contrib/errortracker/sentry/README.md Add the Sentry server middleware to your HTTP server options. It should be placed after the Recovery middleware due to the reversed exit order. ```go import ( "context" ksentry "github.com/go-kratos/kratos/contrib/errortracker/sentry/v3" "github.com/go-kratos/kratos/contrib/otel/v3/tracing" ) // for HTTP server, new HTTP server with sentry middleware options var opts = []http.ServerOption{ http.Middleware( recovery.Recovery(), tracing.Server(), ksentry.Server( ksentry.WithTags(map[string]string{ "tag": "some-custom-constant-tag", }), ksentry.WithContextTags(func(ctx context.Context) map[string]string { return map[string]string{"trace_id": tracing.TraceID(ctx)} }), ), // must after Recovery middleware, because of the exiting order will be reversed logging.Server(logger), ), } ``` -------------------------------- ### Discovery Registry Configuration Structure Source: https://github.com/go-kratos/kratos/blob/main/contrib/registry/discovery/README.md Defines the configuration parameters for the discovery registry, including nodes, region, zone, environment, and hostname. ```go type Config struct { Nodes []string // discovery nodes address Region string // region of the service, sh Zone string // zone of region, sh001 Env string // env of service, dev, prod and etc Host string // hostname of service } ``` -------------------------------- ### OpenTelemetry Logger Handler Source: https://github.com/go-kratos/kratos/blob/main/log/README.md Initializes a logger that bridges slog records to OpenTelemetry Logs using `otel.NewHandler`. Use the core log builder when Kratos logger options are needed. ```go import ( otel "github.com/go-kratos/kratos/contrib/otel/v3/log" "github.com/go-kratos/kratos/v3/log" ) logger := log.NewLogger(otel.NewHandler("helloworld")) log.SetDefault(logger) ``` -------------------------------- ### Initialize slog Logger Source: https://github.com/go-kratos/kratos/blob/main/log/README.md Initializes a new slog JSON handler for standard output and sets it as the default logger. Use this for basic structured logging. ```go logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, })) log.SetDefault(logger) logger.InfoContext(ctx, "user created", "user_id", userID, "service.name", "helloworld", ) ``` -------------------------------- ### Migrate Logging to slog Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md Kratos v3 uses the standard library `log/slog`. Migrate from `log.Logger` to `*slog.Logger` and adapt handler configurations. Use `log.NewLogger` with a `slog.Handler` and optional filters. Set the default logger using `log.SetDefault`. ```go import ( "log/slog" "os" "github.com/go-kratos/kratos/v3/log" ) logger := log.NewLogger( slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, }), log.WithFilter(log.FilterKey("password")), ).With( slog.String("service.name", "helloworld"), slog.String("service.version", "v1.0.0"), ) log.SetDefault(logger) ``` -------------------------------- ### Configure gRPC Server with Sentry Middleware Source: https://github.com/go-kratos/kratos/blob/main/contrib/errortracker/sentry/README.md Add the Sentry server middleware to your gRPC server options. It should be placed after the Recovery middleware due to the reversed exit order. ```go import ( "context" ksentry "github.com/go-kratos/kratos/contrib/errortracker/sentry/v3" "github.com/go-kratos/kratos/contrib/otel/v3/tracing" ) // for gRPC server, new gRPC server with sentry middleware options var opts = []grpc.ServerOption{ grpc.Middleware( recovery.Recovery(), tracing.Server(), ksentry.Server( ksentry.WithTags(map[string]string{ "tag": "some-custom-constant-tag", }), ksentry.WithContextTags(func(ctx context.Context) map[string]string { return map[string]string{"trace_id": tracing.TraceID(ctx)} }), ), // must after Recovery middleware, because of the exiting order will be reversed logging.Server(logger), ), } ``` -------------------------------- ### Conventional Commits - Body Explanation Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md The body provides motivation for the change and contrasts it with previous behavior. It is optional but recommended for complex changes. ```text The body should include the motivation for the change and contrast this with previous behavior. ``` -------------------------------- ### Conventional Commits - Description Guidelines Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md The description should be concise and use the imperative, present tense. Do not capitalize the first letter or end with a period. ```text The description contains a succinct description of the change - use the imperative, present tense: "change" not "changed" nor "changes" - don't capitalize the first letter - no dot (.) at the end ``` -------------------------------- ### Update Kratos Module Paths Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md Update Kratos imports from v2 to v3. Ensure to refresh dependencies after changing import paths. ```go // v2 import "github.com/go-kratos/kratos/v2" // v3 import "github.com/go-kratos/kratos/v3" ``` -------------------------------- ### Create Cluster Role Binding for Kratos Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/kubernetes/README.md Use this command to grant the 'view' cluster role to the 'mesh:default' service account, allowing Kratos to access Kubernetes resources. ```bash kubectl create clusterrolebinding go-kratos:kube --clusterrole=view --serviceaccount=mesh:default ``` -------------------------------- ### Update JWT Middleware Imports Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md JWT middleware has moved to `contrib`. Update your import path from `github.com/go-kratos/kratos/v2/middleware/auth/jwt` to `github.com/go-kratos/kratos/contrib/middleware/jwt/v3`. Remember to update your dependencies. ```go // v2 import "github.com/go-kratos/kratos/v2/middleware/auth/jwt" // v3 import "github.com/go-kratos/kratos/contrib/middleware/jwt/v3" ``` -------------------------------- ### Global Logger Helpers Source: https://github.com/go-kratos/kratos/blob/main/log/README.md Utilize global logger helpers for common logging tasks. These mirror slog signatures, accepting a message followed by key/value pairs or slog.Attr values. ```go log.Info("started") ``` ```go log.Info("listening", "addr", addr) ``` ```go log.Info("service started", "service.name", "helloworld", "service.version", "v1.0.0") ``` ```go log.InfoContext(ctx, "user created", "user_id", userID) ``` -------------------------------- ### Generate Changelog Command Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md Use this command to generate a changelog during development. It helps in tracking changes for releases. ```bash kratos changelog dev ``` -------------------------------- ### Attach Context Attributes Source: https://github.com/go-kratos/kratos/blob/main/log/README.md Attach attributes to a `context.Context` using `log.ContextWithAttrs`. These attributes will automatically flow through any context-aware log calls. ```go ctx = log.ContextWithAttrs(ctx, slog.String("request_id", id)) log.InfoContext(ctx, "handling request") ``` -------------------------------- ### Kubernetes ClusterRoleBinding Definition Source: https://github.com/go-kratos/kratos/blob/main/contrib/config/kubernetes/README.md This YAML defines a ClusterRoleBinding named 'go-kratos:kube' that grants the 'view' role to the 'default' service account in the 'mesh' namespace. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: go-kratos:kube roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: view subjects: - kind: ServiceAccount name: default namespace: mesh ``` -------------------------------- ### Regenerate Kratos Generated Code Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md After updating dependencies and imports, regenerate Kratos generated files using `go generate ./...` and `go mod tidy`. This is crucial for services using generated HTTP clients or servers as v3 code no longer imports the removed HTTP binding package. ```shell go generate ./... go mod tidy ``` -------------------------------- ### Conventional Commits Structure Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md Follow this structure for commit messages to ensure consistency and clarity. The type, scope, and description are mandatory. ```text [optional scope]: [optional body] [optional footer(s)] ``` -------------------------------- ### Custom Circuit Breaker with Aegis Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md If you need to inject a custom Aegis breaker, add Aegis as an explicit dependency. Adapt your injection point to use `circuitbreaker.WithBreakerFactory` and provide a factory function that returns your custom breaker. ```go handler := circuitbreaker.Client( circuitbreaker.WithBreakerFactory(func() circuitbreaker.CircuitBreaker { return newBreaker() }), )(next) ``` -------------------------------- ### Default Circuit Breaker Usage Source: https://github.com/go-kratos/kratos/blob/main/docs/migration/v2-to-v3.md The default circuit breaker no longer depends on `github.com/go-kratos/aegis`. Default usage requires no code changes. ```go handler := circuitbreaker.Client()(next) ``` -------------------------------- ### Conventional Commits - Footer Explanation Source: https://github.com/go-kratos/kratos/blob/main/CONTRIBUTING.md Footers are used for Breaking Changes and referencing issues. Use 'Closes #issue_number' to link commits to issues. ```text The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit Closes. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.