### Install Kratos Tool (go install) Source: https://go-kratos.dev/docs/getting-started/start Install the Kratos command-line tool using 'go install'. This is the recommended method for installing the latest version. ```bash go install github.com/go-kratos/kratos/cmd/kratos/v2@latest ``` -------------------------------- ### Install Wire Source: https://go-kratos.dev/docs/guide/wire Install the Wire tool and import it into your Go project. ```bash # Import into project go get -u github.com/google/wire # Install cmd go install github.com/google/wire/cmd/wire ``` -------------------------------- ### Install proto-gen-validate Source: https://go-kratos.dev/docs/component/middleware/validate Install the proto-gen-validate tool using go install. If errors occur during generation, consider building from source. ```go go install github.com/envoyproxy/protoc-gen-validate@latest ``` -------------------------------- ### Create and Use HTTP Server Router Source: https://go-kratos.dev/docs/component/transport/http Define a route prefix and register HTTP handlers for specific paths using the server's router. This example shows setting up a GET request handler. ```go r := s.Route("/v1") r.GET("/helloworld/{name}", _Greeter_SayHello0_HTTP_Handler(srv)) ``` -------------------------------- ### Compile and Run Kratos Application Source: https://go-kratos.dev/docs/getting-started/start Install the 'wire' tool, generate necessary code, and then run the Kratos application. ```bash # installation dependency go get github.com/google/wire/cmd/wire@latest # generate all codes of proto and wire etc. go generate ./... # run the application kratos run ``` -------------------------------- ### Install Kratos CLI Source: https://go-kratos.dev/docs/getting-started/usage Installs the Kratos command-line interface using go install. Ensure your Go environment is set up correctly. ```bash go install github.com/go-kratos/kratos/cmd/kratos/v2@latest ``` -------------------------------- ### Install Kratos Tool (Source Compilation) Source: https://go-kratos.dev/docs/getting-started/start Alternatively, compile and install Kratos from its source code. This involves cloning the repository and running 'make install'. ```bash git clone https://github.com/go-kratos/kratos cd kratos make install ``` -------------------------------- ### Install protoc-gen-openapi Plugin Source: https://go-kratos.dev/docs/guide/openapi Install the protoc-gen-openapi plugin globally using go install. This is a prerequisite for generating OpenAPI specifications. ```bash go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest ``` -------------------------------- ### Use service discovery Source: https://go-kratos.dev/docs/component/transport/http Example of creating an HTTP client with service discovery. ```APIDOC ## Use service discovery ### Example ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("discovery:///helloworld"), http.WithDiscovery(r), ) ``` ``` -------------------------------- ### Start HTTP Server with Kratos Source: https://go-kratos.dev/docs/component/transport/http Initialize a new Kratos HTTP server and register it with the Kratos application. This sets up the basic HTTP server instance. ```go hs := http.NewServer() app := kratos.New( kratos.Name("kratos"), kratos.Version("v1.0.0"), kratos.Server(hs), ) ``` -------------------------------- ### Use middleware Source: https://go-kratos.dev/docs/component/transport/http Example of creating an HTTP client with middleware. ```APIDOC ## Use middleware ### Example ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("127.0.0.1:9000"), http.WithMiddleware( recovery.Recovery(), ), ) ``` ``` -------------------------------- ### Example: gRPC Client with JWT Source: https://go-kratos.dev/docs/component/middleware/auth Demonstrates setting up a gRPC client with JWT authentication, connecting to a service that uses the same signing key and method. ```go con, _ := grpc.DialInsecure( context.Background(), grpc.WithEndpoint("dns:///127.0.0.1:9001"), // Services for local port 9001 grpc.WithMiddleware( jwt.Client(func(token *jwtv4.Token) (interface{}, error) { return []byte(serviceTestKey), nil }), ), ) ``` -------------------------------- ### Example Configuration Files Source: https://go-kratos.dev/docs/component/config Demonstrates two configuration files with overlapping keys and their merged output, illustrating Kratos' configuration merging behavior where root-level keys from later files overwrite those from earlier ones. ```yaml # File 1 foo: baz: "2" biu: "example" hello: a: b ``` ```yaml # File 2 foo: bar: 3 baz: aaaa hey: good: bad qux: quux ``` ```json { "foo": { "baz": "aaaa", "bar": 3, "biu": "example" }, "hey": { "good": "bad", "qux": "quux" }, "hello": { "a": "b" } } ``` -------------------------------- ### Kratos Version Output Source: https://go-kratos.dev/docs/getting-started/usage Example output showing the Kratos tool version. ```text kratos version v2.2.1 ``` -------------------------------- ### Create a client connection Source: https://go-kratos.dev/docs/component/transport/http Example of creating a new HTTP client connection. ```APIDOC ## Create a client connection ### Example ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("127.0.0.1:8000"), ) ``` ``` -------------------------------- ### Install protoc-gen-validate Source: https://go-kratos.dev/docs/intro/faq Use this command to build the protoc-gen-validate plugin. Ensure you are in the cloned repository directory. ```bash git clone github.com/envoyproxy/protoc-gen-validate cd protoc-gen-validate make build ``` -------------------------------- ### Install Ent CLI Source: https://go-kratos.dev/docs/guide/ent Use this command to install the Ent command-line interface tool. ```bash go install entgo.io/ent/cmd/ent@latest ``` -------------------------------- ### JSON Codec Implementation Example Source: https://go-kratos.dev/docs/component/encoding Example of a JSON Codec implementation, handling both standard JSON and protobuf messages. It uses configurable MarshalOptions and UnmarshalOptions. ```go package json import ( "encoding/json" "reflect" "github.com/go-kratos/kratos/v2/encoding" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) // Name is the name registered for the json codec. const Name = "json" var ( // MarshalOptions is a configurable JSON format marshaller. MarshalOptions = protojson.MarshalOptions{ EmitUnpopulated: true, } // UnmarshalOptions is a configurable JSON format parser. UnmarshalOptions = protojson.UnmarshalOptions{ DiscardUnknown: true, } ) func init() { encoding.RegisterCodec(codec{}) } // codec is a Codec implementation with json. type codec struct{} func (codec) Marshal(v interface{}) ([]byte, error) { switch m := v.(type) { case json.Marshaler: return m.MarshalJSON() case proto.Message: return MarshalOptions.Marshal(m) default: return json.Marshal(m) } } func (codec) Unmarshal(data []byte, v interface{}) error { switch m := v.(type) { case json.Unmarshaler: return m.UnmarshalJSON(data) case proto.Message: return UnmarshalOptions.Unmarshal(data, m) default: rv := reflect.ValueOf(v) for rv := rv; rv.Kind() == reflect.Ptr; { if rv.IsNil() { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok { return UnmarshalOptions.Unmarshal(data, m) } return json.Unmarshal(data, m) } } func (codec) Name() string { return Name } ``` -------------------------------- ### Changelog Example Source: https://go-kratos.dev/docs/community/contribution An example of a changelog generated for development, including new features and other updates. ```markdown ### New Features - feat(cmd): add kratos changelog command (#1140) - feat(examples): add benchmark example (#1134) - feat: add int/int32/Stringer support when get atomicValue (#1130) ### Others - add form encoding (#1138) - upgrade otel to v1 rc1 (#1132) - http stop should use ctx (#1131) ``` -------------------------------- ### Create HTTP Client Connection Source: https://go-kratos.dev/docs/component/transport/http Establishes a new HTTP client connection to a specified endpoint. This is the basic setup for initiating communication. ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("127.0.0.1:8000"), ) ``` -------------------------------- ### Configure gRPC Server with Tracing Source: https://go-kratos.dev/docs/component/middleware/logging Example of configuring a gRPC server with tracing middleware, which is often used in conjunction with logging. ```go exporter, err := stdouttrace.New(stdouttrace.WithWriter(ioutil.Discard)) if err != nil { fmt.Printf("creating stdout exporter: %v", err) panic(err) } tp := tracesdk.NewTracerProvider( tracesdk.WithBatcher(exporter), tracesdk.WithResource(resource.NewSchemaless( semconv.ServiceNameKey.String(Name)), ) ) var opts = []grpc.ServerOption{ grpc.Middleware( tracing.Server(tracing.WithTracerProvider(tp)), ), } srv := grpc.NewServer(opts...) ``` -------------------------------- ### Create HTTP Client with Middleware Source: https://go-kratos.dev/docs/component/transport/http Creates an HTTP client connection and applies middleware for request/response processing. The recovery middleware is included as an example. ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("127.0.0.1:9000"), http.WithMiddleware( recovery.Recovery(), ), ) ``` -------------------------------- ### Define Service in Proto File Source: https://go-kratos.dev/docs/getting-started/usage Example of a proto file defining a service with RPC methods and request/reply messages. This is used for generating Go code. ```proto syntax = "proto3"; package api.helloworld; option go_package = "helloworld/api/api/helloworld;helloworld"; option java_multiple_files = true; option java_package = "api.helloworld"; service Demo { rpc CreateDemo (CreateDemoRequest) returns (CreateDemoReply); rpc UpdateDemo (UpdateDemoRequest) returns (UpdateDemoReply); rpc DeleteDemo (DeleteDemoRequest) returns (DeleteDemoReply); rpc GetDemo (GetDemoRequest) returns (GetDemoReply); rpc ListDemo (ListDemoRequest) returns (ListDemoReply); } message CreateDemoRequest {} message CreateDemoReply {} message UpdateDemoRequest {} message UpdateDemoReply {} message DeleteDemoRequest {} message DeleteDemoReply {} message GetDemoRequest {} message GetDemoReply {} message ListDemoRequest {} message ListDemoReply {} ``` -------------------------------- ### Install protoc-gen-go-errors Source: https://go-kratos.dev/docs/component/errors Installs the protoc-gen-go-errors plugin, which is used for generating error types from proto definitions. ```bash go install github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2 ``` -------------------------------- ### Server Interface for Lifecycle Management Source: https://go-kratos.dev/docs/component/transport/overview Defines the Start and Stop methods for managing the server lifecycle. This interface is fundamental for any server implementation within Kratos. ```go type Server interface { Start(context.Context) error Stop(context.Context) error } ``` -------------------------------- ### HTTP API Registration Source: https://go-kratos.dev/docs/component/api Example of how to register the generated Greeter HTTP handler with an HTTP server. ```APIDOC import "github.com/go-kratos/kratos/v2/transport/http" greeter := &GreeterService{} srv := http.NewServer(http.Address(":8000")) srv.HandlePrefix("/", v1.NewGreeterHandler(greeter)) ``` -------------------------------- ### gRPC API Registration Source: https://go-kratos.dev/docs/component/api Example of how to register the generated Greeter gRPC service with a gRPC server. ```APIDOC import "github.com/go-kratos/kratos/v2/transport/grpc" greeter := &GreeterService{} srv := grpc.NewServer(grpc.Address(":9000")) v1.RegisterGreeterServer(srv, greeter) ``` -------------------------------- ### Print Logs with log.Helper Source: https://go-kratos.dev/docs/component/log Provides examples of printing logs at different levels (Debug, Info, Warn, Error, Fatal) using the `log.Helper`. Note that `Fatal` level interrupts program execution. ```go h.Debug("Are you OK?") h.Info("42 is the answer to life, the universe, and everything") h.Warn("We are under attack!") h.Error("Houston, we have a problem.") h.Fatal("So Long, and Thanks for All the Fish.") ``` -------------------------------- ### View Kratos Tool Version Source: https://go-kratos.dev/docs/getting-started/usage Displays the current version of the Kratos tool. This command is useful for verifying installation and compatibility. ```bash kratos -v ``` -------------------------------- ### gRPC Server Recovery Configuration Source: https://go-kratos.dev/docs/component/middleware/recovery Example of configuring the Recovery middleware for a gRPC server. It demonstrates how to set up a custom logger and an exception handler. ```go var opts = []grpc.ServerOption{ grpc.Middleware( recovery.Recovery( recovery.WithLogger(log.DefaultLogger), recovery.WithHandler(func(ctx context.Context, req, err interface{}) error { // do someting return nil }), ), ), } srv := grpc.NewServer(opts...) ``` -------------------------------- ### NewServer Source: https://go-kratos.dev/docs/component/transport/grpc Constructs a new gRPC server with the provided options. It applies default configurations and custom options, registers health and metadata services, and starts listening. ```APIDOC ## NewServer Constructs a new gRPC server. ### Signature ```go func NewServer(opts ...ServerOption) *Server ``` ### Description Initializes a gRPC server with default settings and applies provided `ServerOption`s. It configures interceptors, TLS, and registers necessary services like health and reflection. ### Example Usage ```go // Assuming ServerOption and other necessary types are defined server := grpc.NewServer( grpc.Network("tcp"), grpc.Address(":8080"), grpc.Timeout(5 * time.Second), grpc.Middleware(myMiddleware), ) ``` ``` -------------------------------- ### HTTP Server Recovery Configuration Source: https://go-kratos.dev/docs/component/middleware/recovery Example of configuring the Recovery middleware for an HTTP server. It includes setting a custom logger and a handler for exceptions. ```go var opts = []http.ServerOption{ http.Middleware( recovery.Recovery( recovery.WithLogger(log.DefaultLogger), recovery.WithHandler(func(ctx context.Context, req, err interface{}) error { // do someting return nil }), ), ), } srv := http.NewServer(opts...) ``` -------------------------------- ### Configure JSON Marshaling for HTTP Responses Source: https://go-kratos.dev/docs/intro/faq Import necessary packages and set `protojson.MarshalOptions` in the init method to control how protobuf messages are marshaled to JSON for HTTP responses. This example configures options to emit unpopulated fields and use proto names. ```go import ( "github.com/go-kratos/kratos/v2/encoding/json" "google.golang.org/protobuf/encoding/protojson" ) ``` ```go func init() { flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml") //Add this code json.MarshalOptions = protojson.MarshalOptions{ EmitUnpopulated: true, //Default value not ignored UseProtoNames: true, //Use proto name to return http field } } ``` -------------------------------- ### HTTP Server Metrics Integration Source: https://go-kratos.dev/docs/component/metrics Example of integrating Prometheus metrics into an HTTP server using Kratos middleware. Requires importing necessary packages and defining a Prometheus CounterVec. ```go import ( "github.com/go-kratos/kratos/v2/middleware" kmetrics "github.com/go-kratos/prometheus/metrics" "github.com/go-kratos/kratos/v2/middleware/metrics" "github.com/go-kratos/kratos/v2/transport/http" "github.com/prometheus/client_golang/prometheus" ) func NewHTTPServer(c *conf.Server) *http.Server { // for prometheus counter := prometheus.NewCounterVec(prometheus.CounterOpts{Name: "kratos_counter"}, []string{"server", "qps"}) var opts = []http.ServerOption{ http.Middleware( middleware.Chain( recovery.Recovery(), metrics.Server(metrics.WithRequests(kmetrics.NewCounter(counter))), ), ), } ``` -------------------------------- ### Create New Kratos Project Source: https://go-kratos.dev/docs/getting-started/start Create a new Kratos project with the specified name ('helloworld') and download its dependencies. ```bash # create project's layout kratos new helloworld cd helloworld # pull dependencies go mod download ``` -------------------------------- ### Initialize Logger with Fluentd Source: https://go-kratos.dev/docs/component/log Demonstrates initializing a logger using the fluentd plugin. This requires importing the fluentd logger implementation and configuring the connection. ```go import "github.com/go-kratos/kratos/contrib/log/fluent/v2" import "github.com/go-kratos/kratos/v2/log" logger, err := fluent.NewLogger("unix:///var/run/fluent/fluent.sock") if err != nil { return } h := log.NewHelper(logger) ``` -------------------------------- ### NewServer Source: https://go-kratos.dev/docs/component/transport/http Initializes a new HTTP server with provided options. ```APIDOC ## NewServer(opts ...ServerOption) *Server ### Description Pass in opts configuration and start HTTP Server. ### Usage ```go hs := http.NewServer() app := kratos.New( kratos.Name("kratos"), kratos.Version("v1.0.0"), kratos.Server(hs), ) ``` ### Example with Middleware ```go hs := http.NewServer( http.Address(":8000"), http.Middleware( logging.Server(), ), ) ``` ``` -------------------------------- ### Initialize Logger with Helper Source: https://go-kratos.dev/docs/component/log Shows how to initialize a `log.Helper` with a custom logger or the default logger. The `log.Helper` simplifies log message formatting and level handling. ```go import "github.com/go-kratos/kratos/v2/log" h := log.NewHelper(yourlogger) // You can use the default logger directly h := log.NewHelper(log.DefaultLogger) ``` -------------------------------- ### Application Entry Point and DI Configuration Source: https://go-kratos.dev/docs/guide/wire Defines the application's entry point and configures dependency injection using `wire.Build`. ```go // the entry point of the application func newApp(logger log.Logger, hs *http.Server, gs *grpc.Server, greeter *service.GreeterService) *kratos.App { pb.RegisterGreeterServer(gs, greeter) pb.RegisterGreeterHTTPServer(hs, greeter) return kratos.New( kratos.Name(Name), kratos.Version(Version), kratos.Logger(logger), kratos.Server( hs, gs, ), ) } // wire.go initialization func initApp(*conf.Server, *conf.Data, log.Logger) (*kratos.App, error) { // builds ProviderSet in every modules, for the generation of wire_gen.go panic(wire.Build(server.ProviderSet, data.ProviderSet, biz.ProviderSet, service.ProviderSet, newApp)) } ``` -------------------------------- ### Initialize File Configuration Source Source: https://go-kratos.dev/docs/component/config Loads configuration from a local file or directory. Specify the path to a single file or a directory containing configuration files. ```go import ( "github.com/go-kratos/kratos/v2/config" "github.com/go-kratos/kratos/v2/config/file" ) path := "configs/config.yaml" c := config.New( config.WithSource( file.NewSource(path), ), ) ``` -------------------------------- ### Get Codec by Name Source: https://go-kratos.dev/docs/component/encoding Retrieve a registered Codec implementation using its registered name. ```go jsonCodec := encoding.GetCodec("json") ``` -------------------------------- ### Standard Output and File Logging Source: https://go-kratos.dev/docs/component/log Demonstrates how to log to standard output using the default logger and how to configure logging to a file by passing an `io.Writer` to `NewStdLogger`. ```go //Output to console l := log.DefaultLogged l.Log(log.LevelInfo, "stdout_key", "stdout_value") // Output to ./test.log file f, err := os.OpenFile("test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { return } l = log.NewStdLogger(f) l.Log(log.LevelInfo, "file_key", "file_value") ``` -------------------------------- ### Using Helper for Logging Source: https://go-kratos.dev/docs/component/log Demonstrates basic usage of the Helper interface for logging messages with different levels and formatting. ```go helper.Info("hello") helper.Errorf("hello %s", "eric") ``` -------------------------------- ### Register Service with Consul Source: https://go-kratos.dev/docs/component/registry Demonstrates how to create a Consul client and registrar, then integrate it with a Kratos application for automatic service registration. ```go import ( consul "github.com/go-kratos/consul/registry" "github.com/hashicorp/consul/api" ) // new consul client client, err := api.NewClient(api.DefaultConfig()) if err != nil { panic(err) } // new reg with consul client reg := consul.New(client) app := kratos.New( // service-name kratos.Name(Name), kratos.Version(Version), kratos.Metadata(map[string]string{}), kratos.Logger(logger), kratos.Server( hs, gs, ), // with registrar kratos.Registrar(reg), ) ``` -------------------------------- ### SayHello RPC Source: https://go-kratos.dev/docs/component/api Defines the SayHello RPC method for the Greeter service, including HTTP GET and POST bindings. ```APIDOC ## GET /helloworld/{name} ### Description Sends a greeting to the specified name. ### Method GET ### Endpoint /helloworld/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. ### Response #### Success Response (200) - **message** (string) - The greeting message. ## POST /v1/greeter/say_hello ### Description Sends a greeting to the specified name using a request body. ### Method POST ### Endpoint /v1/greeter/say_hello ### Parameters #### Request Body - **name** (string) - Required - The name to greet. ### Response #### Success Response (200) - **message** (string) - The greeting message. ``` -------------------------------- ### Service Discovery (gRPC) with etcd Source: https://go-kratos.dev/docs/component/registry Shows how to set up a gRPC client to discover services using etcd as the discovery backend. Ensure to use DialInsecure or appropriate credentials. ```go import ( "github.com/go-kratos/kratos/contrib/registry/etcd/v2" "github.com/go-kratos/kratos/v2/transport/grpc" clientv3 "go.etcd.io/etcd/client/v3" ) // new etcd client client, err := clientv3.New(clientv3.Config{ Endpoints: []string{"127.0.0.1:2379"}, }) if err != nil { panic(err) } // new dis with etcd client dis := etcd.New(client) // This Dial need to use DialInsecure() or use grpc.WithTransportCredentials in Dial option endpoint := "discovery:///provider" conn, err := grpc.Dial(context.Background(), grpc.WithEndpoint(endpoint), grpc.WithDiscovery(dis)) if err != nil { panic(err) } ``` -------------------------------- ### Create New Kratos Project Source: https://go-kratos.dev/docs/getting-started/usage Initializes a new Kratos project. You can specify a custom layout repository using the -r flag, or use environment variables. ```bash kratos new helloworld ``` ```bash # If pull fails in China, you can use gitee source. kratos new helloworld -r https://gitee.com/go-kratos/kratos-layout.git ``` ```bash # You can also use custom templates kratos new helloworld -r xxx-layout.git ``` ```bash # You can also specify the source through the environment variable KRATOS_LAYOUT_REPO=xxx-layout.git kratos new helloworld ``` ```bash kratos new helloworld -b main ``` ```bash kratos new helloworld cd helloworld kratos new app/user --nomod ``` -------------------------------- ### Log Error with Contextual Trace ID Source: https://go-kratos.dev/docs/component/middleware/logging Example of logging an error message that includes the trace ID from the current context. ```go log.WithContext(ctx).Errorf("Field created: %s", err) ``` -------------------------------- ### Create HTTP Client with Service Discovery Source: https://go-kratos.dev/docs/component/transport/http Initializes an HTTP client that uses service discovery to find endpoints. The `WithDiscovery` option integrates a service registry. ```go conn, err := http.NewClient( context.Background(), http.WithEndpoint("discovery:///helloworld"), http.WithDiscovery(r), ) ``` -------------------------------- ### Greeter Service - SayHello RPC Source: https://go-kratos.dev/docs/intro/design Defines a gRPC service 'Greeter' with a 'SayHello' method that also exposes an HTTP GET endpoint. ```APIDOC ## SayHello RPC ### Description Sends a greeting to the specified name. ### Method GET ### Endpoint /helloworld/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **message** (string) - The greeting message. ### Response Example ```json { "message": "Hello, [name]!" } ``` ``` -------------------------------- ### Implementing and Using Logger Interface Source: https://go-kratos.dev/docs/component/log Shows how to implement the Logger interface and use it to log messages with key-value pairs. ```go logger.Log(log.LevelInfo, "msg", "hello", "instance_id", 123) ``` -------------------------------- ### Register Service with etcd Source: https://go-kratos.dev/docs/component/registry Shows how to set up an etcd client and registrar for use with Kratos applications, enabling service registration. ```go import ( "github.com/go-kratos/kratos/contrib/registry/etcd/v2" clientv3 "go.etcd.io/etcd/client/v3" ) // new etcd client client, err := clientv3.New(clientv3.Config{ Endpoints: []string{"127.0.0.1:2379"}, }) if err != nil { panic(err) } // new reg with etcd client reg := etcd.New(client) app := kratos.New( // service-name kratos.Name(Name), kratos.Version(Version), kratos.Metadata(map[string]string{}), kratos.Logger(logger), kratos.Server( hs, gs, ), // with registrar kratos.Registrar(reg), ) ``` -------------------------------- ### Configure HTTP Client Logging Source: https://go-kratos.dev/docs/component/middleware/logging Use `logging.Client()` within `http.WithMiddleware` to log details of initiated HTTP requests. ```go logger := log.DefaultLogger conn, err := http.NewClient( context.Background(), http.WithMiddleware( logging.Client(logger), ), http.WithEndpoint("127.0.0.1:8000"), ) ``` -------------------------------- ### Create New Kratos Project Source: https://go-kratos.dev/docs/intro/layout Use this command to generate a new project with the predefined Kratos layout. This command sets up the directory structure and initial files for your microservice. ```bash kratos new ``` -------------------------------- ### Get Specific Configuration Value Source: https://go-kratos.dev/docs/component/config Retrieves the value of a specific configuration field using its key. Supports string conversion and error handling. ```go name, err := c.Value("service.name").String() if err != nil { panic(err) } fmt.Printf("service: %s", name) ``` -------------------------------- ### Registering HTTP Server with Kratos Application Source: https://go-kratos.dev/docs/component/transport/overview Demonstrates how to register an HTTP server implementation with a Kratos application. Ensure the 'httpSrv' variable is properly initialized before use. ```go app := kratos.New( kratos.Name(Name), kratos.Server( httpSrv, ), ) ``` -------------------------------- ### Get Metadata Value from Server Context Source: https://go-kratos.dev/docs/component/metadata Retrieve a metadata value from the server context using its key. Ensure the context is valid and the metadata exists. ```go if md, ok := metadata.FromServerContext(ctx); ok { extra = md.Get("x-md-global-extra") } ``` -------------------------------- ### Register gRPC Server Source: https://go-kratos.dev/docs/component/transport/grpc Demonstrates how to create a new gRPC server instance and integrate it with a Kratos application. ```APIDOC ## Register gRPC Server This section shows how to initialize a gRPC server and register it with the Kratos application. ### Code Example ```go gs := grpc.NewServer() app := kratos.New( kratos.Name("kratos"), kratos.Version("v1.0.0"), kratos.Server(gs), ) ``` ``` -------------------------------- ### Proto Validation Rule for Messages Source: https://go-kratos.dev/docs/component/middleware/validate Ensure that a message field is present and not unset using the 'required' rule. This example also shows a nested message definition. ```proto // info cannot be unset Info info = 11 [(validate.rules).message.required = true]; message Info { string address = 1; } ``` -------------------------------- ### Full Conventional Commit Message Example Source: https://go-kratos.dev/docs/community/contribution A comprehensive commit message including type, scope, description, body, and footers for breaking changes and issue references. ```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 ``` -------------------------------- ### JSON Deserialization Example Source: https://go-kratos.dev/docs/component/encoding Deserialize JSON bytes into a Go struct using a registered Codec. Ensure the JSON encoding package is imported if used directly. ```go // You should manually import this package if you use it directly:import _ "github.com/go-kratos/kratos/v2/encoding/json" jsonCodec := encoding.GetCodec("json") type user struct { Name string Age string state bool } u := &user{} jsonCodec.Unmarshal([]byte(`{"Name":"kratos","Age":"2"}`), &u) fmt.Println(*u) //output &{kratos 2 false} ``` -------------------------------- ### JSON Serialization Example Source: https://go-kratos.dev/docs/component/encoding Serialize a Go struct into JSON bytes using a registered Codec. Ensure the JSON encoding package is imported if used directly. ```go // You should manually import this package if you use it directly: import _ "github.com/go-kratos/kratos/v2/encoding/json" jsonCodec := encoding.GetCodec("json") type user struct { Name string Age string state bool } u := &user{ Name: "kratos", Age: "2", state: false, } bytes, _ := jsonCodec.Marshal(u) fmt.Println(string(bytes)) // output {"Name":"kratos","Age":"2"} ``` -------------------------------- ### Run Kratos Project Source: https://go-kratos.dev/docs/getting-started/usage Executes the Kratos project. If multiple items exist under a subdirectory, a selection menu will appear. ```bash kratos run ``` -------------------------------- ### Key-Value Log Printing with log.Helper Source: https://go-kratos.dev/docs/component/log Demonstrates printing logs with custom key-value pairs using methods ending in 'w' (e.g., `Debugw`, `Infow`). This is useful for structured logging. ```go h.Debugw("custom_key", "Are you OK?") h.Infow("custom_key", "42 is the answer to life, the universe, and everything") h.Warnw("custom_key", "We are under attack!") h.Errorw("custom_key", "Houston, we have a problem.") h.Fatalw("custom_key", "So Long, and Thanks for All the Fish.") ``` -------------------------------- ### Error Structure Example Source: https://go-kratos.dev/docs/component/errors Illustrates the JSON structure for errors, including code, reason, message, and metadata. This format is used for converting between gRPC and HTTP error codes. ```json { // The error code is consistent with HTTP status and can be converted into grpc status in grpc. "code": 500, // The error reason is defined as the business judgment error code. "reason": "USER_NOT_FOUND", // Error information is user-readable information and can be used as user prompt content. "message": "invalid argument error", // Error meta information, add additional extensible information for the error. "metadata": { "foo": "bar" } } ``` -------------------------------- ### Basic gRPC Client Connection Source: https://go-kratos.dev/docs/component/transport/grpc Establishes a basic insecure gRPC client connection to a specified endpoint. Use this for simple client setups where security is handled at a different layer. ```go conn, err := grpc.DialInsecure( context.Background(), grpc.WithEndpoint("127.0.0.1:9000"), ) ``` -------------------------------- ### Build Docker Image Source: https://go-kratos.dev/docs/devops/docker Build your Docker image using the Dockerfile in the current directory. Replace with your desired image name. ```bash docker build -t . ``` -------------------------------- ### Generated Go Error Handling Code Source: https://go-kratos.dev/docs/component/errors Example of Go code generated from proto definitions. It includes helper functions like IsUserNotFound and ErrorUserNotFound for checking and creating specific errors. ```go package helloworld import ( fmt "fmt" errors "github.com/go-kratos/kratos/v2/errors" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the kratos package it is being compiled against. const _ = errors.SupportPackageIsVersion1 func IsUserNotFound(err error) bool { if err == nil { return false } e := errors.FromError(err) return e.Reason == ErrorReason_USER_NOT_FOUND.String() && e.Code == 404 } func ErrorUserNotFound(format string, args ...interface{}) *errors.Error { return errors.New(404, ErrorReason_USER_NOT_FOUND.String(), fmt.Sprintf(format, args...)) } func IsContentMissing(err error) bool { if err == nil { return false } e := errors.FromError(err) return e.Reason == ErrorReason_CONTENT_MISSING.String() && e.Code == 400 } func ErrorContentMissing(format string, args ...interface{}) *errors.Error { return errors.New(400, ErrorReason_CONTENT_MISSING.String(), fmt.Sprintf(format, args...)) } ``` -------------------------------- ### Initialize Consul Configuration Source Source: https://go-kratos.dev/docs/component/config Connects to a Consul agent to load configuration. Ensure Consul is running and accessible at the specified address. Configuration is loaded from a specified path within Consul. ```go import ( "github.com/go-kratos/kratos/contrib/config/consul/v2" "github.com/hashicorp/consul/api" ) 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/")) if err != nil { panic(err) } c := config.New(config.WithSource(cs)) ``` -------------------------------- ### Prometheus Metrics Initialization (kratos >= 2.8.0) Source: https://go-kratos.dev/docs/component/middleware/metrics Initializes OpenTelemetry metric providers and meters for Prometheus export, setting up default request counters and duration histograms. ```go import ( "github.com/go-kratos/kratos/v2/middleware/metrics" "go.opentelemetry.io/otel/exporters/prometheus" "go.opentelemetry.io/otel/metric" sdkmetric "go.opentelemetry.io/otel/sdk/metric" ) // Detailed reference https://github.com/go-kratos/examples/tree/main/metrics func init() { exporter, err := prometheus.New() if err != nil { panic(err) } provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(exporter)) meter := provider.Meter(Name) _metricRequests, err = metrics.DefaultRequestsCounter(meter, metrics.DefaultServerRequestsCounterName) if err != nil { panic(err) } _metricSeconds, err = metrics.DefaultSecondsHistogram(meter, metrics.DefaultServerSecondsHistogramName) if err != nil { panic(err) } } ``` -------------------------------- ### Register gRPC Server Source: https://go-kratos.dev/docs/component/transport/grpc Instantiate a new gRPC server and register it with the Kratos application. ```go gs := grpc.NewServer() app := kratos.New( kratos.Name("kratos"), kratos.Version("v1.0.0"), kratos.Server(gs), ) ``` -------------------------------- ### Configure gRPC Client Logging Source: https://go-kratos.dev/docs/component/middleware/logging Pass `logging.Client()` to `http.ServerOption` to enable detailed logging for outgoing gRPC requests. Note: The example uses `http.ServerOption` which might be a typo in the source and intended for `grpc.ClientOption`. ```go logger := log.DefaultLogger var opts = []http.ServerOption{ http.Middleware( logging.Server(logger), ), } srv := http.NewServer(opts...) ``` -------------------------------- ### HTTP Client Metrics Integration Source: https://go-kratos.dev/docs/component/metrics Example of integrating Prometheus metrics into an HTTP client using Kratos middleware. This involves setting up a Prometheus CounterVec and applying it to the client's middleware chain. ```go import ( "context" "github.com/go-kratos/kratos/v2/middleware" kmetrics "github.com/go-kratos/prometheus/metrics" "github.com/go-kratos/kratos/v2/middleware/metrics" "github.com/go-kratos/kratos/v2/transport/http" "github.com/prometheus/client_golang/prometheus" ) func useClient() { counter := prometheus.NewCounterVec(prometheus.CounterOpts{Name: "kratos_counter"}, []string{"client", "qps"}) client, _ := http.NewClient(context.Background(), http.WithMiddleware(metrics.Client(metrics.WithRequests(kmetrics.NewCounter(counter))))) // ... } ``` -------------------------------- ### Add Proto Files to Project Source: https://go-kratos.dev/docs/getting-started/usage Adds a new proto file to your Kratos project. Specify the path where the proto file should be created. ```bash kratos proto add api/helloworld/demo.proto ``` -------------------------------- ### Run Docker Container Source: https://go-kratos.dev/docs/devops/docker Run your Docker container, mapping ports and mounting a volume for configuration. Replace and with your specific paths and image name. ```bash docker run --rm -p 8000:8000 -p 9000:9000 -v :/data/conf ``` -------------------------------- ### Configure Enum Marshaling for HTTP Responses Source: https://go-kratos.dev/docs/intro/faq Import necessary packages and set `protojson.MarshalOptions` in the init method to control enum representation in JSON HTTP responses. This example configures options to use enum numbers. ```go import ( "github.com/go-kratos/kratos/v2/encoding/json" "google.golang.org/protobuf/encoding/protojson" ) ``` ```go func init() { flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml") // Add this code json.MarshalOptions = protojson.MarshalOptions{ UseEnumNumbers: true, // UseEnumNumbers emits enum values as numbers. } } ``` -------------------------------- ### Prometheus Metrics Initialization (kratos < 2.8.0) Source: https://go-kratos.dev/docs/component/middleware/metrics Initializes Prometheus HistogramVec and CounterVec for tracking request duration and counts. These metrics are then registered with Prometheus. ```go // Detailed reference https://github.com/go-kratos/examples/tree/main/metrics _metricSeconds = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "server", Subsystem: "requests", Name: "duration_sec", Help: "server requests duratio(sec).", Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.250, 0.5, 1}, }, []string{"kind", "operation"}) _metricRequests = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "client", Subsystem: "requests", Name: "code_total", Help: "The total number of processed requests", }, []string{"kind", "operation", "code", "reason"}) prometheus.MustRegister(_metricSeconds, _metricRequests) ``` -------------------------------- ### Enable Go Modules Source: https://go-kratos.dev/docs/getting-started/start Ensure Go modules are enabled by setting the GO111MODULE environment variable to 'on'. ```bash go env -w GO111MODULE=on ``` -------------------------------- ### NewServer: Create a gRPC Server Source: https://go-kratos.dev/docs/component/transport/grpc Constructs a new gRPC server with default configurations and applies provided options. It converts middleware and TLS configurations into gRPC server options and registers health and reflection services. ```go func NewServer(opts ...ServerOption) *Server { // grpc server default configuration srv := &Server{ network: "tcp", address: ":0", timeout: 1 * time.Second, health: health.NewServer(), log: log.NewHelper(log.GetLogger()), } // apply opts for _, o := range opts { o(srv) } // convert middleware to grpc interceptor unaryInts := []grpc.UnaryServerInterceptor{ srv.unaryServerInterceptor(), } streamInts := []grpc.StreamServerInterceptor{ srv.streamServerInterceptor(), } if len(srv.unaryInts) > 0 { unaryInts = append(unaryInts, srv.unaryInts...) } if len(srv.streamInts) > 0 { streamInts = append(streamInts, srv.streamInts...) } // convert UnaryInterceptor and StreamInterceptor to ServerOption var grpcOpts = []grpc.ServerOption{ grpc.ChainUnaryInterceptor(unaryInts...), grpc.ChainStreamInterceptor(streamInts...), } // convert LTS config to ServerOption if srv.tlsConf != nil { grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(srv.tlsConf))) } // convert srv.grpcOpts to ServerOption if len(srv.grpcOpts) > 0 { grpcOpts = append(grpcOpts, srv.grpcOpts...) } // create grpc server srv.Server = grpc.NewServer(grpcOpts...) // create metadata server srv.metadata = apimd.NewServer(srv.Server) // set lis and endpoint srv.err = srv.listenAndEndpoint() // register these internal API grpc_health_v1.RegisterHealthServer(srv.Server, srv.health) apimd.RegisterMetadataServer(srv.Server, srv.metadata) reflection.Register(srv.Server) return srv } ``` -------------------------------- ### Dockerfile for Go Kratos Application Source: https://go-kratos.dev/docs/devops/docker This multi-stage Dockerfile builds a Go Kratos application, optimizing for smaller image size. It uses a builder stage with the Go toolchain and a final slim Debian stage for the application binary. ```dockerfile FROM golang:1.19 AS builder COPY . /src WORKDIR /src RUN GOPROXY=https://goproxy.cn make build FROM debian:stable-slim RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/ \ && apt-get autoremove -y && apt-get autoclean -y COPY --from=builder /src/bin /app WORKDIR /app EXPOSE 8000 EXPOSE 9000 VOLUME /data/conf CMD ["./server", "-conf", "/data/conf"] ``` -------------------------------- ### Generate DI Codes Source: https://go-kratos.dev/docs/guide/wire Run the `go generate` command to create the dependency injection code. ```bash go generate ./... ``` -------------------------------- ### HTTP Server Options Source: https://go-kratos.dev/docs/component/transport/http Configure the Kratos HTTP server using various ServerOption functions. ```APIDOC ## HTTP Server Configuration Options ### Network Configures the network protocol of the server (e.g., `tcp`). ```go Network(network string) ServerOption ``` ### Address Configures the server listening address. ```go Address(addr string) ServerOption ``` ### Timeout Configures server timeout settings. ```go Timeout(timeout time.Duration) ServerOption ``` ### Logger Configures the logger used in the HTTP server. ```go Logger(logger log.Logger) ServerOption ``` ### Middleware Configures the Kratos service middleware on the server side. ```go Middleware(m ...middleware.Middleware) ServerOption ``` ### Filter Configures the server-side Kratos global HTTP native Filter. The execution order of this Filter is before the Service middleware. ```go Filter(filters ...FilterFunc) ServerOption ``` ### RequestDecoder Configures the HTTP Request Decode method of the Kratos server to parse the Request Body into a user-defined pb structure. The default implementation handles different Content-Types. ```go RequestDecoder(dec DecodeRequestFunc) ServerOption ``` **Default RequestDecoder Implementation:** ```go func DefaultRequestDecoder(r *http.Request, v interface{}) error { // Extract the corresponding decoder from the Content-Type of the Request Header codec, ok := CodecForRequest(r, "Content-Type") // If the corresponding decoder cannot be found, an error will be reported at this time if !ok { return errors.BadRequest("CODEC", r.Header.Get("Content-Type")) } data, err := ioutil.ReadAll(r.Body) if err != nil { return errors.BadRequest("CODEC", err.Error()) } if err = codec.Unmarshal(data, v); err != nil { return errors.BadRequest("CODEC", err.Error()) } return nil } ``` ### ResponseEncoder Configures the HTTP Response Encode method of the Kratos server to serialize the reply structure in the user pb definition and write it into the Response Body. The default implementation uses the `Accept` header to determine the encoder. ```go ResponseEncoder(en EncodeResponseFunc) ServerOption ``` **Default ResponseEncoder Implementation:** ```go func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error { // Extract the corresponding encoder from the Accept of Request Header // If not found, ignore the error and use the default json encoder codec, _ := CodecForRequest(r, "Accept") data, err := codec.Marshal(v) if err != nil { return err } // Write the scheme of the encoder in the Response Header w.Header().Set("Content-Type", httputil.ContentType(codec.Name())) w.Write(data) return nil } ``` ### ErrorEncoder Configures the HTTP Error Encode method of the Kratos server to serialize the error thrown by the business and write it into the Response Body, and set the HTTP Status Code. ```go ErrorEncoder(en EncodeErrorFunc) ServerOption ``` **Default ErrorEncoder Implementation:** ```go func DefaultErrorEncoder(w http.ResponseWriter, r *http.Request, err error) { // Get error and convert it into kratos Error entity se := errors.FromError(err) // Extract the corresponding encoder from the Accept of Request Header codec, _ := CodecForRequest(r, "Accept") body, err := codec.Marshal(se) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Content-Type", httputil.ContentType(codec.Name())) // Set HTTP Status Code w.WriteHeader(int(se.Code)) w.Write(body) } ``` ### TLSConfig Configures the TLSConfig of the Kratos to encrypting HTTP traffic. ```go TLSConfig(c *tls.Config) ServerOption ``` **TLSConfig Implementation:** ```go // TLSConfig with TLS config. func TLSConfig(c *tls.Config) ServerOption { return func(o *Server) { o.tlsConf = c } } ``` ```