怎么混合使用gin框架和grpc框架写一个web服务并运行
时间: 2024-05-02 10:16:55 浏览: 177
可以按照以下步骤来混合使用gin框架和grpc框架写一个web服务并运行:
1. 安装gin和grpc框架:
```bash
go get -u github.com/gin-gonic/gin
go get -u google.golang.org/grpc
```
2. 创建一个grpc服务:
```go
package main
import (
"context"
"fmt"
"net"
pb "path/to/your/proto" // 导入你的protobuf文件
"google.golang.org/grpc"
)
type server struct{}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
panic(err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
fmt.Println("grpc server started on port 50051...")
if err := s.Serve(lis); err != nil {
panic(err)
}
}
```
3. 创建一个gin服务:
```go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World!",
})
})
fmt.Println("gin server started on port 8080...")
router.Run(":8080")
}
```
4. 将grpc服务和gin服务结合:
```go
package main
import (
"context"
"fmt"
"net"
pb "path/to/your/proto" // 导入你的protobuf文件
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
)
type server struct{}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
func main() {
// grpc server
go func() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
panic(err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
fmt.Println("grpc server started on port 50051...")
if err := s.Serve(lis); err != nil {
panic(err)
}
}()
// gin server
router := gin.Default()
router.GET("/", func(c *gin.Context) {
// grpc client
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
client := pb.NewGreeterClient(conn)
// call grpc service
resp, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "world"})
if err != nil {
panic(err)
}
c.JSON(200, gin.H{
"message": resp.Message,
})
})
fmt.Println("gin server started on port 8080...")
router.Run(":8080")
}
```
5. 运行服务:
```bash
go run main.go
```
现在,你就可以通过访问 `http://localhost:8080`,来调用grpc服务并获取响应了。
阅读全文