Created
June 2, 2024 03:29
-
-
Save kvii/108d26b83955fd28f4faa56bba3a344f to your computer and use it in GitHub Desktop.
kratos 获取 header。同时支持 http 和 grpc。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"github.com/go-kratos/examples/helloworld/helloworld" | |
"github.com/go-kratos/kratos/v2/transport/grpc" | |
"github.com/go-kratos/kratos/v2/transport/http" | |
) | |
func main() { | |
// 客户端 | |
ctx := context.Background() | |
reqHttp(ctx) | |
reqGrpc(ctx) | |
} | |
func reqHttp(ctx context.Context) { | |
cli, _ := http.NewClient(ctx, http.WithEndpoint("127.0.0.1:8000")) | |
hc := helloworld.NewGreeterHTTPClient(cli) | |
reply, err := hc.SayHello(ctx, &helloworld.HelloRequest{ | |
Name: "http", | |
}) | |
log.Println(reply, err) | |
} | |
func reqGrpc(ctx context.Context) { | |
conn, _ := grpc.DialInsecure(ctx, grpc.WithEndpoint("127.0.0.1:9000")) | |
hc := helloworld.NewGreeterClient(conn) | |
reply, err := hc.SayHello(ctx, &helloworld.HelloRequest{ | |
Name: "grpc", | |
}) | |
log.Println(reply, err) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"log/slog" | |
"github.com/go-kratos/examples/helloworld/helloworld" | |
"github.com/go-kratos/kratos/v2" | |
"github.com/go-kratos/kratos/v2/transport" | |
"github.com/go-kratos/kratos/v2/transport/grpc" | |
"github.com/go-kratos/kratos/v2/transport/http" | |
) | |
type server struct { | |
helloworld.UnimplementedGreeterServer | |
} | |
func (server) SayHello(ctx context.Context, req *helloworld.HelloRequest) (*helloworld.HelloReply, error) { | |
if tr, ok := transport.FromServerContext(ctx); ok { // 关键代码 | |
k := "User-Agent" | |
ct := tr.RequestHeader().Get(k) | |
slog.InfoContext(ctx, "header", slog.String(k, ct)) | |
} | |
return &helloworld.HelloReply{Message: "Hello " + req.Name}, nil | |
} | |
func main() { | |
// 服务端 | |
s := new(server) | |
hs := http.NewServer(http.Address(":8000")) | |
helloworld.RegisterGreeterHTTPServer(hs, s) | |
gs := grpc.NewServer(grpc.Address(":9000")) | |
helloworld.RegisterGreeterServer(gs, s) | |
app := kratos.New(kratos.Server(hs, gs)) | |
if err := app.Run(); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment