1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-03-31 22:05:08 +02:00

69 lines
1.5 KiB
Go
Raw Normal View History

2021-03-05 23:49:25 +08:00
package main
import (
"context"
"fmt"
"log"
2021-03-05 23:49:25 +08:00
"github.com/go-kratos/kratos/examples/helloworld/helloworld"
2021-03-05 23:49:25 +08:00
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/middleware/recovery"
"github.com/go-kratos/kratos/v2/transport/grpc"
"github.com/go-kratos/kratos/v2/transport/http"
)
// go build -ldflags "-X main.Version=x.y.z"
var (
// Name is the name of the compiled software.
Name = "helloworld"
// Version is the version of the compiled software.
Version = "v1.0.0"
)
2021-03-05 23:49:25 +08:00
// server is used to implement helloworld.GreeterServer.
type server struct {
helloworld.UnimplementedGreeterServer
2021-03-05 23:49:25 +08:00
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
2021-03-05 23:49:25 +08:00
if in.Name == "error" {
return nil, errors.BadRequest("custom_error", fmt.Sprintf("invalid argument %s", in.Name))
2021-03-05 23:49:25 +08:00
}
if in.Name == "panic" {
panic("server panic")
2021-03-05 23:49:25 +08:00
}
return &helloworld.HelloReply{Message: fmt.Sprintf("Hello %+v", in.Name)}, nil
2021-03-05 23:49:25 +08:00
}
func main() {
s := &server{}
2021-03-05 23:49:25 +08:00
grpcSrv := grpc.NewServer(
grpc.Address(":9000"),
grpc.Middleware(
2021-05-20 23:30:50 +08:00
recovery.Recovery(),
),
)
httpSrv := http.NewServer(
http.Address(":8000"),
2021-03-05 23:49:25 +08:00
http.Middleware(
2021-05-20 23:30:50 +08:00
recovery.Recovery(),
),
2021-03-05 23:49:25 +08:00
)
helloworld.RegisterGreeterServer(grpcSrv, s)
helloworld.RegisterGreeterHTTPServer(httpSrv, s)
2021-03-05 23:49:25 +08:00
app := kratos.New(
kratos.Name(Name),
2021-03-05 23:49:25 +08:00
kratos.Server(
httpSrv,
grpcSrv,
),
)
if err := app.Run(); err != nil {
log.Fatal(err)
2021-03-05 23:49:25 +08:00
}
}