### Install protobuf compiler (protoc) Source: https://github.com/go-kit/kit/blob/master/transport/grpc/README.md Steps to install the protobuf compiler (protoc) from source using Homebrew and Git. This is necessary for compiling .proto files. ```sh brew install autoconf automake libtool git clone https://github.com/google/protobuf cd protobuf ./autogen.sh ; ./configure ; make ; make install ``` -------------------------------- ### Trace Database Query with Zipkin in Go-kit Source: https://github.com/go-kit/kit/blob/master/tracing/zipkin/README.md Provides an example of how to trace a database query using Zipkin within a Go-kit service. It shows how to start a span, annotate it with query details and timing, and finish it. ```go import ( zipkin "github.com/openzipkin/zipkin-go" ) func (svc *Service) GetMeSomeExamples(ctx context.Context, ...) ([]Examples, error) { // Example of annotating a database query: var ( spanContext model.SpanContext serviceName = "MySQL" serviceHost = "mysql.example.com:3306" queryLabel = "GetExamplesByParam" query = "select * from example where param = :value" ) // retrieve the parent span from context to use as parent if available. if parentSpan := zipkin.SpanFromContext(ctx); parentSpan != nil { spanContext = parentSpan.Context() } // create the remote Zipkin endpoint ep, _ := zipkin.NewEndpoint(serviceName, serviceHost) // create a new span to record the resource interaction span := zipkin.StartSpan( queryLabel, zipkin.Parent(parentSpan.Context()), zipkin.WithRemoteEndpoint(ep), ) // add interesting key/value pair to our span span.SetTag("query", query) // add interesting timed event to our span span.Annotate(time.Now(), "query:start") // do the actual query... // let's annotate the end... span.Annotate(time.Now(), "query:end") // we're done with this span. span.Finish() // do other stuff ... } ``` -------------------------------- ### Contextual Loggers with Go-Kit Source: https://github.com/go-kit/kit/blob/master/log/README.md Illustrates creating contextual loggers in Go-Kit by adding key-value pairs to a base logger. This example adds 'instance_id' and 'component' to log messages. ```Go func main() { var logger log.Logger logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) logger = log.With(logger, "instance_id", 123) logger.Log("msg", "starting") NewWorker(log.With(logger, "component", "worker")).Run() NewSlacker(log.With(logger, "component", "slacker")).Run() } // Output: // instance_id=123 msg=starting // instance_id=123 component=worker msg=running // instance_id=123 component=slacker msg=running ``` -------------------------------- ### Go-Kit JSON RPC Server Setup Source: https://github.com/go-kit/kit/blob/master/transport/http/jsonrpc/README.md Demonstrates how to set up a Go-Kit JSON RPC server. It involves creating an EndpointCodecMap to route incoming JSON RPC methods to specific endpoints, decoders, and encoders. The server is then registered as an HTTP handler. ```Go handler := jsonrpc.NewServer(jsonrpc.EndpointCodecMap{ "sum": jsonrpc.EndpointCodec{ Endpoint: sumEndpoint, Decode: decodeSumRequest, Encode: encodeSumResponse, }, }) http.Handle("/rpc", handler) http.ListenAndServe(":80", nil) ``` -------------------------------- ### Compile Thrift IDL to Go Source: https://github.com/go-kit/kit/blob/master/transport/thrift/README.md This command compiles a Thrift IDL file into Go source code. It uses the Thrift compiler with specific generation flags, including a package prefix for the generated Go code. Ensure you have the Thrift compiler installed and the .thrift file is correctly defined. ```Shell thrift -r --gen go:package_prefix=github.com/my-org/my-repo/thrift/gen-go/ add.thrift ``` -------------------------------- ### Go-Kit JSON RPC EndpointCodecMap Example Source: https://github.com/go-kit/kit/blob/master/transport/http/jsonrpc/README.md Illustrates the structure of an `EndpointCodecMap` in Go-Kit for JSON RPC. It maps a JSON RPC method name (e.g., "sum") to an `EndpointCodec`, which bundles the endpoint logic with request decoding and response encoding functions. ```Go jsonrpc.EndpointCodecMap{ "sum": jsonrpc.EndpointCodec{ Endpoint: sumEndpoint, Decode: decodeSumRequest, Encode: encodeSumResponse, }, } ``` -------------------------------- ### Go-Kit: Monitoring and Instrumentation with spacemonkeygo/monitor Source: https://github.com/go-kit/kit/blob/master/README.md Uses spacemonkeygo/monitor for data collection, monitoring, and instrumentation, including a Zipkin client library. This facilitates performance tracking and distributed tracing. ```Go package main import ( "fmt" "github.com/spacemonkeygo/monitor/monitorlib" "github.com/spacemonkeygo/monitor/tracing/zipkin" "time" ) func main() { // Initialize monitor with Zipkin tracing zipkinClient, err := zipkin.NewClient("my-service", "localhost:9411") // Zipkin collector address if err != nil { panic(err) } monitorlib.SetGlobalMonitor(monitorlib.NewMonitor(zipkinClient)) // Start a trace span span := monitorlib.NewSpan("process_request") defer span.Finish() // Simulate work time.Sleep(100 * time.Millisecond) fmt.Println("Request processed with monitoring.") } ``` -------------------------------- ### Go-Kit: Application Tracing with Appdash Source: https://github.com/go-kit/kit/blob/master/README.md Integrates Appdash for application tracing, inspired by Google's Dapper. It helps visualize request flows and identify performance bottlenecks in distributed systems. ```Go package main import ( "fmt" "net/http" "sourcegraph.com/sourcegraph/appdash" "sourcegraph.com/sourcegraph/appdash/traceapp" ) func main() { // Set up the Appdash collector collector := appdash.NewMemoryCollector() tracer := appdash.NewTracer(collector) // Start the trace viewer web UI go traceapp.RunTraceApp(collector, ":63730") // Example: Trace an HTTP request http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { span, ok := appdash.SpanFromContext(r.Context()) if !ok { span = tracer.StartSpan("root") defer span.Finish() r = r.WithContext(appdash.NewContext(r.Context(), span)) } fmt.Fprintf(w, "Hello from Go-Kit!") subSpan := span.NewChild("response_written") subSpan.Finish() }) fmt.Println("Starting server on :8080, trace viewer on :63730") // http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Go: Counter using expvar Source: https://github.com/go-kit/kit/blob/master/metrics/README.md Demonstrates how to create and use a simple counter metric exported via expvar. This involves initializing the counter and adding a value to it. ```go import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/expvar" ) func main() { var myCount metrics.Counter myCount = expvar.NewCounter("my_count") myCount.Add(1) } ``` -------------------------------- ### Go-Kit: Structured Logging with logrus Source: https://github.com/go-kit/kit/blob/master/README.md Leverages logrus for structured, pluggable logging in Go. It offers flexibility with different output formats and hooks for custom processing. ```Go package main import ( "github.com/sirupsen/logrus" ) func main() { // Create a new logger instance log := logrus.New() // Set output to stdout log.SetOutput(os.Stdout) // Set formatter (e.g., JSONFormatter) log.SetFormatter(&logrus.JSONFormatter{}) // Log messages with fields log.WithFields(logrus.Fields{ "event": "login", "user_id": 42, }).Info("User successfully logged in") log.Warn("Potential issue detected") } ``` -------------------------------- ### Go-Kit: Structured Logging with log15 Source: https://github.com/go-kit/kit/blob/master/README.md Employs the log15 library for simple and powerful structured logging in Go applications. It supports various handlers for outputting logs. ```Go package main import ( "github.com/inconshreveable/log15" "os" ) func main() { // Create a logger with a handler that writes to stdout log := log15.New() log.SetHandler(log15.StreamHandler(os.Stdout, log15.LogfmtFormat())) // Log messages with context log.Info("User logged in", "user_id", 123, "ip", "192.168.1.1") log.Error("Failed to process request", "error", "timeout", "request_id", "abc") } ``` -------------------------------- ### Go-Kit: Nanomsg Implementation with mangos Source: https://github.com/go-kit/kit/blob/master/README.md Provides a pure Go implementation of Nanomsg (nanomsg) messaging patterns using the mangos library. It enables high-performance asynchronous messaging. ```Go package main import ( "fmt" "log" "github.com/gdamore/mangos" _ "github.com/gdamore/mangos/protocol/reqrep" _ "github.com/gdamore/mangos/transport/tcp" ) func main() { sock, err := mangos.NewSocket(mangos.REQ) if err != nil { log.Fatalf("cannot create new socket: %v", err) } // Ensure socket is closed defer sock.Close() // Connect to the address if err = sock.Dial("tcp://localhost:8081"); err != nil { log.Fatalf("cannot dial: %v", err) } // Send a message msg := []byte("Hello Nanomsg!") if err = sock.Send(msg); err != nil { log.Fatalf("cannot send: %v", err) } // Receive a reply reply, err := sock.Recv() if err != nil { log.Fatalf("cannot recv: %v", err) } fmt.Printf("Received reply: %s\n", reply) } ``` -------------------------------- ### Basic Logfmt Logger Usage in Go-Kit Source: https://github.com/go-kit/kit/blob/master/log/README.md Shows how to create and use a basic logfmt logger with Go-Kit. It logs a question and answer to standard error. ```Go w := log.NewSyncWriter(os.Stderr) logger := log.NewLogfmtLogger(w) logger.Log("question", "what is the meaning of life?", "answer", 42) // Output: // question="what is the meaning of life?" answer=42 ``` -------------------------------- ### Go-Kit: HTTP Handler Filters with handy Source: https://github.com/go-kit/kit/blob/master/README.md Applies net/http handler filters using the handy library. This allows for middleware-like functionality to wrap HTTP handlers for cross-cutting concerns. ```Go package main import ( "fmt" "net/http" "github.com/streadway/handy" ) func main() { // Define a simple handler mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from main handler!") }) // Create a filter (e.g., logging) loggingFilter := handy.LoggingHandler(os.Stdout, mainHandler) // Create another filter (e.g., method check) methodFilter := handy.MethodHandler("GET", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "This is a GET request.") })) // Chain filters chainedHandler := handy.Chain(loggingFilter, methodFilter) http.Handle("/", chainedHandler) fmt.Println("Server starting on :8080...") // http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Go: Histogram using Prometheus Summary Source: https://github.com/go-kit/kit/blob/master/metrics/README.md Shows how to create a histogram for request duration using a Prometheus Summary. It includes setting up the SummaryOpts with namespace, subsystem, name, and help text, and observing the duration. ```go import ( time "time" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" ) func main() { var dur metrics.Histogram = prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ Namespace: "myservice", Subsystem: "api", Name: "request_duration_seconds", Help: "Total time spent serving requests.", }, []string{}) // ... } func handleRequest(dur metrics.Histogram) { defer func(begin time.Time) { dur.Observe(time.Since(begin).Seconds()) }(time.Now()) // handle request } ``` -------------------------------- ### Go-Kit: Client-side Fault Tolerance with Hystrix-Go Source: https://github.com/go-kit/kit/blob/master/README.md Integrates the hystrix-go library for implementing client-side latency and fault tolerance patterns within Go applications. This helps manage failures and improve system resilience. ```Go package main import ( "fmt" "github.com/afex/hystrix-go/hystrix" ) func main() { // Configure a circuit breaker hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{ Timeout: 1000, MaxConcurrentRequests: 100, ErrorPercentThreshold: 25, }) // Execute a command err := hystrix.Do("my_command", func() error { // Your command logic here fmt.Println("Executing command...") return nil }, func(err error) error { // Fallback logic here fmt.Println("Executing fallback...") return nil }) if err != nil { fmt.Printf("Error executing command: %v\n", err) } } ``` -------------------------------- ### Go-Kit HTTP Basic Auth Middleware Usage Source: https://github.com/go-kit/kit/blob/master/auth/basic/README.md Demonstrates how to integrate the Basic Authentication middleware into a Go-Kit HTTP server. It shows the necessary import, the middleware's placement in the server creation, and the requirement for context population. ```go import httptransport "github.com/go-kit/kit/transport/http" httptransport.NewServer( AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()), decodeMappingsRequest, httptransport.EncodeJSONResponse, httptransport.ServerBefore(httptransport.PopulateRequestContext), ) ``` -------------------------------- ### Structured vs. Unstructured Logging in Go-Kit Source: https://github.com/go-kit/kit/blob/master/log/README.md Demonstrates the difference between unstructured and structured logging using the Go-Kit log package. Structured logging uses key-value pairs for contextual information. ```Go // Unstructured log.Printf("HTTP server listening on %s", addr) // Structured logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") ``` -------------------------------- ### Go-Kit: Metrics Exporting with go-metrics Source: https://github.com/go-kit/kit/blob/master/README.md Utilizes the go-metrics library to export performance and runtime metrics to external systems. This enables monitoring and analysis of application behavior. ```Go package main import ( "fmt" "github.com/armon/go-metrics" "time" ) func main() { // Initialize metrics registry metrics.NewGlobalMetricRegistry(nil) // Create a counter requests, _ := metrics.NewCounter("requests_total") // Increment the counter requests.Inc(1) // Create a timer latency, _ := metrics.NewTimer("request_latency_seconds") // Record a duration latency.Record(50 * time.Millisecond) fmt.Println("Metrics recorded.") } ``` -------------------------------- ### Redirecting Go-Kit Logger to Stdlib Logger Source: https://github.com/go-kit/kit/blob/master/log/README.md Shows how to pipe Go-Kit logger output through the standard library's log package for legacy systems. ```Go logger := kitlog.NewLogfmtLogger(kitlog.StdlibWriter{}) logger.Log("legacy", true, "msg", "at least it's something") // Output: // 2016/01/01 12:34:56 legacy=true msg="at least it's something" ``` -------------------------------- ### Redirecting Stdlib Logger to Go-Kit JSON Logger Source: https://github.com/go-kit/kit/blob/master/log/README.md Demonstrates how to redirect the standard library's log output to a Go-Kit JSON logger using an adapter. ```Go import ( os stdlog "log" kitlog "github.com/go-kit/kit/log" ) func main() { logger := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout)) stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) stdlog.Print("I sure like pie") } // Output: // {"msg":"I sure like pie","ts":"2016/01/01 12:34:56"} ``` -------------------------------- ### Go-Kit: RPC with context.Context using rpcplus Source: https://github.com/go-kit/kit/blob/master/README.md Utilizes the rpcplus package for enhanced RPC functionality, including support for context.Context. This allows for request-scoped values and cancellation propagation. ```Go package main import ( "context" "fmt" "net/rpc" "github.com/youtube/vitess/go/rpcplus" ) // Define arguments and results for the RPC method type Args struct { A, B int } type Reply struct { C int } // Define a service type MathService int func (t *MathService) Add(ctx context.Context, args *Args, reply *Reply) error { reply.C = args.A + args.B return nil } func main() { // Register the service math := new(MathService) rpcplus.Register(math) // Example of calling the service (typically done client-side) client, err := rpcplus.Dial("tcp", "localhost:1234") if err != nil { fmt.Printf("dialing %v\n", err) return } args := &Args{1, 2} reply := new(Reply) // Call the Add method with context ctx := context.Background() err = client.Call(ctx, "MathService.Add", args, reply) if err != nil { fmt.Printf("Error calling Add: %v\n", err) } else { fmt.Printf("Math: %d + %d = %d\n", args.A, args.B, reply.C) } } ``` -------------------------------- ### Configure Zipkin HTTP Reporter in Go-kit Source: https://github.com/go-kit/kit/blob/master/tracing/zipkin/README.md Demonstrates how to configure the Zipkin HTTP reporter in a Go-kit service. It involves creating a reporter, defining the service's local endpoint, and initializing the tracer. ```go var ( serviceName = "MyService" serviceHostPort = "localhost:8000" zipkinHTTPEndpoint = "http://localhost:9411/api/v2/spans" ) // create an instance of the HTTP Reporter. reporter := zipkin.NewReporter(zipkinHTTPEndpoint) // create our tracer's local endpoint (how the service is identified in Zipkin). localEndpoint, err := zipkin.NewEndpoint(serviceName, serviceHostPort) // create our tracer instance. tracer, err = zipkin.NewTracer(reporter, zipkin.WithLocalEndpoint(localEndpoint)) ... ``` -------------------------------- ### Go-Kit Zipkin Tracing Source: https://github.com/go-kit/kit/blob/master/tracing/README.md Provides bindings to the native Go tracing implementation for Zipkin. This is the preferred binding for polyglot microservices environments. Instrumentation exists for kit/transport/http and kit/transport/grpc. ```Go package tracing // Zipkin provides bindings to the native Go tracing implementation [zipkin-go]. // Instrumentation exists for `kit/transport/http` and `kit/transport/grpc`. ``` -------------------------------- ### Go-Kit: RPC with gRPC-Go Source: https://github.com/go-kit/kit/blob/master/README.md Utilizes gRPC-Go for building high-performance, HTTP/2-based Remote Procedure Call (RPC) services. It supports features like protocol buffers for efficient data serialization. ```Go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" // Assuming you have a protobuf generated package // "path/to/your/proto" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() // Create a client // client := pb.NewYourServiceClient(conn) // Call a remote procedure // resp, err := client.YourMethod(context.Background(), &pb.YourRequest{Name: "Go-Kit"}) // if err != nil { // log.Fatalf("could not greet: %v", err) // } // fmt.Printf("Response: %s\n", resp.GetMessage()) fmt.Println("gRPC client setup complete (example).") } ``` -------------------------------- ### Go-Kit: Resiliency Patterns with go-resiliency Source: https://github.com/go-kit/kit/blob/master/README.md Implements various resiliency patterns using the go-resiliency library. This includes strategies like retries, timeouts, and circuit breakers to enhance application robustness. ```Go package main import ( "fmt" "github.com/eapache/go-resiliency/retrier" "time" ) func main() { // Configure a retrier r := retrier.New(2*time.Second, 3) // 2-second delay, 3 retries // Attempt an operation with retries err := r.Run(func() error { // Your operation that might fail fmt.Println("Attempting operation...") return fmt.Errorf("operation failed") }) if err != nil { fmt.Printf("Operation failed after multiple retries: %v\n", err) } else { fmt.Println("Operation succeeded.") } } ``` -------------------------------- ### Go-Kit OpenTracing Tracing Source: https://github.com/go-kit/kit/blob/master/tracing/README.md Supports the OpenTracing API and uses the opentracing-go package to provide tracing middlewares for its servers and clients. Instrumentation exists for kit/transport/http and kit/transport/grpc. Supports multiple tracing backends through the OpenTracing interface. ```Go package tracing // Go kit supports the [OpenTracing] API and uses the [opentracing-go] package to provide tracing middlewares for its servers and clients. // Currently OpenTracing instrumentation exists for `kit/transport/http` and `kit/transport/grpc`. ``` -------------------------------- ### Go-Kit OpenCensus Tracing Source: https://github.com/go-kit/kit/blob/master/tracing/README.md Supports transport and endpoint middlewares for the OpenCensus instrumentation library. OpenCensus provides a cross-language consistent data model and instrumentation libraries for tracing and metrics, allowing exports to various backends. ```Go package tracing // Go kit supports transport and endpoint middlewares for the [OpenCensus] instrumentation library. // Go kit uses the [opencensus-go] implementation to power its middlewares. ``` -------------------------------- ### Run Zipkin with Docker Source: https://github.com/go-kit/kit/blob/master/tracing/zipkin/README.md This snippet shows how to run a Zipkin server using a Docker container. It exposes the default HTTP collector and web UI on port 9411. ```bash docker run -d -p 9411:9411 openzipkin/zipkin ``` -------------------------------- ### Compile protobuf to Go with gRPC Source: https://github.com/go-kit/kit/blob/master/transport/grpc/README.md Command to compile a .proto file into Go source files with gRPC support using the protoc compiler. This generates the necessary Go code for gRPC communication. ```sh protoc add.proto --go_out=plugins=grpc:. ``` -------------------------------- ### Go: Gauge using StatsD Source: https://github.com/go-kit/kit/blob/master/metrics/README.md Illustrates creating a gauge to track the number of goroutines, exported via StatsD. It sets up a StatsD client, a send loop, and a goroutine to periodically update the gauge with the current goroutine count. ```go import ( "context" "net" "os" "runtime" "time" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/statsd" ) func main() { statsd := statsd.New("foo_svc.", log.NewNopLogger()) report := time.NewTicker(5 * time.Second) defer report.Stop() go statsd.SendLoop(context.Background(), report.C, "tcp", "statsd.internal:8125") goroutines := statsd.NewGauge("goroutine_count") go exportGoroutines(goroutines) // ... } func exportGoroutines(g metrics.Gauge) { for range time.Tick(time.Second) { g.Set(float64(runtime.NumGoroutine())) } } ``` -------------------------------- ### Go-Kit OpenTelemetry Tracing Source: https://github.com/go-kit/kit/blob/master/tracing/README.md Provides Go kit instrumentation through the opentelemetry-go-contrib repository, which is a central repository of instrumentation libraries. OpenTelemetry merged OpenCensus and OpenTracing. ```Go package tracing // Go kit instrumentation can be found in [opentelemetry-go-contrib] // which is a central repository of instrumentation libraries. ``` -------------------------------- ### Go: JWT Signing Middleware Source: https://github.com/go-kit/kit/blob/master/auth/jwt/README.md Creates an endpoint middleware that signs JWTs for outgoing requests. It takes a key ID header, signing key, signing method, and claims object to construct the token. ```go import ( stdjwt "github.com/golang-jwt/jwt/v4" "github.com/go-kit/kit/auth/jwt" "github.com/go-kit/kit/endpoint" ) func main() { var exampleEndpoint endpoint.Endpoint { exampleEndpoint = grpctransport.NewClient(...).Endpoint() exampleEndpoint = jwt.NewSigner( "kid-header", []byte("SigningString"), stdjwt.SigningMethodHS256, jwt.Claims{}, )(exampleEndpoint) } } ``` -------------------------------- ### Adding Timestamps and Callers with Go-Kit Logger Source: https://github.com/go-kit/kit/blob/master/log/README.md Configures a Go-Kit logger to automatically include UTC timestamps and caller information in log messages. ```Go var logger log.Logger logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) logger.Log("msg", "hello") // Output: // ts=2016-01-01T12:34:56Z caller=main.go:15 msg=hello ``` -------------------------------- ### Go-Kit Logger Interface Definition Source: https://github.com/go-kit/kit/blob/master/log/README.md Defines the core Logger interface in the Go-Kit log package, which accepts a variable number of key-value pairs. ```Go type Logger interface { Log(keyvals ...interface{}) error } ``` -------------------------------- ### Go: JWT Token Parsing Middleware Source: https://github.com/go-kit/kit/blob/master/auth/jwt/README.md Creates an endpoint middleware that parses a JWT from the request context. It requires a key function to verify the token's signature and an expected signing method. Valid claims are added to the context. ```go import ( stdjwt "github.com/golang-jwt/jwt/v4" "github.com/go-kit/kit/auth/jwt" "github.com/go-kit/kit/endpoint" ) func main() { var exampleEndpoint endpoint.Endpoint { kf := func(token *stdjwt.Token) (interface{}, error) { return []byte("SigningString"), nil } exampleEndpoint = MakeExampleEndpoint(service) exampleEndpoint = jwt.NewParser(kf, stdjwt.SigningMethodHS256, jwt.StandardClaimsFactory)(exampleEndpoint) } } ``` -------------------------------- ### Go: JWT Context to gRPC Transport Source: https://github.com/go-kit/kit/blob/master/auth/jwt/README.md Helper function to transfer JWT information from the context to the gRPC transport layer. Used as a ClientBefore option for gRPC clients. ```go import ( stdjwt "github.com/golang-jwt/jwt/v4" grpctransport "github.com/go-kit/kit/transport/grpc" "github.com/go-kit/kit/auth/jwt" "github.com/go-kit/kit/endpoint" ) func main() { options := []httptransport.ClientOption{} var exampleEndpoint endpoint.Endpoint { exampleEndpoint = grpctransport.NewClient(..., grpctransport.ClientBefore(jwt.ContextToGRPC())).Endpoint() exampleEndpoint = jwt.NewSigner( "kid-header", []byte("SigningString"), stdjwt.SigningMethodHS256, jwt.Claims{}, )(exampleEndpoint) } } ``` -------------------------------- ### Go: JWT gRPC Transport to Context Source: https://github.com/go-kit/kit/blob/master/auth/jwt/README.md Helper function to transfer JWT information from the gRPC transport layer to the context. Used as a ServerBefore option for gRPC servers. ```go import ( "context" "github.com/go-kit/kit/auth/jwt" "github.com/go-kit/log" grpctransport "github.com/go-kit/kit/transport/grpc" ) func MakeGRPCServer(ctx context.Context, endpoints Endpoints, logger log.Logger) pb.ExampleServer { options := []grpctransport.ServerOption{grpctransport.ServerErrorLogger(logger)} return &grpcServer{ createUser: grpctransport.NewServer( ctx, endpoints.CreateUserEndpoint, DecodeGRPCCreateUserRequest, EncodeGRPCCreateUserResponse, append(options, grpctransport.ServerBefore(jwt.GRPCToContext())). ), getUser: grpctransport.NewServer( ctx, endpoints.GetUserEndpoint, DecodeGRPCGetUserRequest, EncodeGRPCGetUserResponse, options ), } } ``` -------------------------------- ### Go-Kit JSON RPC Request Decoder Source: https://github.com/go-kit/kit/blob/master/transport/http/jsonrpc/README.md Defines a `DecodeRequestFunc` for Go-Kit's JSON RPC server. This function takes raw JSON parameters from a JSON RPC request, unmarshals them into a specific Go struct (e.g., `SumRequest`), and returns it as an interface{}. ```Go type SumRequest struct { A, B int } func decodeSumRequest(ctx context.Context, msg json.RawMessage) (interface{}, error) { var req SumRequest err := json.Unmarshal(msg, &req) if err != nil { return nil, err } return req, nil } ``` -------------------------------- ### Go-Kit JSON RPC Response Encoder Source: https://github.com/go-kit/kit/blob/master/transport/http/jsonrpc/README.md Defines an `EncodeResponseFunc` for Go-Kit's JSON RPC server. This function takes the result from an endpoint (expected to be an int in this case), marshals it into JSON, and returns it as `json.RawMessage` to be included in the JSON RPC response. ```Go func encodeSumResponse(ctx context.Context, result interface{}) (json.RawMessage, error) { sum, ok := result.(int) if !ok { return nil, errors.New("result is not an int") } b, err := json.Marshal(sum) if err != nil { return nil, err } return b, nil } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.