user-srv/Server/gw-server.go

61 lines
1.2 KiB
Go

package server
import (
"context"
"fmt"
"net/http"
"user-srv/config"
pb "user-srv/pb/api"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
func StartGwServer() error {
conn, err := grpc.DialContext(
context.Background(),
fmt.Sprintf("%v:%v", config.GrpcAddress, config.GrpcPort), //grpc 动态地址
grpc.WithBlock(),
grpc.WithInsecure(),
)
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "ContactGroupDetail",
}).Warnf("grpc.DialContext: %s", err)
return err
}
mux := runtime.NewServeMux()
err = pb.RegisterUserServiceHandler(context.Background(), mux, conn)
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "ContactGroupDetail",
}).Warnf("pb.RegisterUserServiceHandler: %s", err)
return err
}
// 启动网关
server := &http.Server{
Addr: config.GatewayAddress,
Handler: mux,
}
//日志
logrus.WithFields(logrus.Fields{
"func": "ContactGroupDetail",
}).Infof("Start gRPC Gateway Server on: %s", config.GatewayAddress)
err = server.ListenAndServe()
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "ContactGroupDetail",
}).Warnf("server.ListenAndServe: %s", err)
return err
}
return nil
}