You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
kratos/examples/helloworld/client/main.go

76 lines
1.8 KiB

package main
import (
"context"
"log"
pb "github.com/go-kratos/kratos/examples/helloworld/helloworld"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/middleware/recovery"
transgrpc "github.com/go-kratos/kratos/v2/transport/grpc"
transhttp "github.com/go-kratos/kratos/v2/transport/http"
)
func main() {
callHTTP()
callGRPC()
}
func callHTTP() {
conn, err := transhttp.NewClient(
context.Background(),
transhttp.WithMiddleware(
recovery.Recovery(),
),
transhttp.WithEndpoint("127.0.0.1:8000"),
)
if err != nil {
log.Fatal(err)
}
client := pb.NewGreeterHTTPClient(conn)
reply, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "kratos"})
if err != nil {
log.Fatal(err)
}
log.Printf("[http] SayHello %s\n", reply.Message)
// returns error
reply, err = client.SayHello(context.Background(), &pb.HelloRequest{Name: "error"})
if err != nil {
log.Printf("[http] SayHello error: %v\n", err)
}
if errors.IsBadRequest(err) {
log.Printf("[http] SayHello error is invalid argument: %v\n", err)
}
}
func callGRPC() {
conn, err := transgrpc.DialInsecure(
context.Background(),
transgrpc.WithEndpoint("127.0.0.1:9000"),
transgrpc.WithMiddleware(
middleware.Chain(
recovery.Recovery(),
),
),
)
if err != nil {
log.Fatal(err)
}
client := pb.NewGreeterClient(conn)
reply, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "kratos"})
if err != nil {
log.Fatal(err)
}
log.Printf("[grpc] SayHello %+v\n", reply)
// returns error
_, err = client.SayHello(context.Background(), &pb.HelloRequest{Name: "error"})
if err != nil {
log.Printf("[grpc] SayHello error: %v\n", err)
}
if errors.IsBadRequest(err) {
log.Printf("[grpc] SayHello error is invalid argument: %v\n", err)
}
}