add gateway

This commit is contained in:
2025-03-30 13:23:46 +08:00
parent ca00b34e24
commit 93daa022bc
4 changed files with 53 additions and 14 deletions

View File

@@ -30,6 +30,17 @@ func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) {
return nil, errcode.ErrJWTAuthNotFound
}
// 安全获取 metadata 中的值
identityValues := md.Get("authorization_identity")
clientValues := md.Get("client")
if len(identityValues) == 0 {
return nil, errcode.ErrJWTAuthNotFound
}
if len(clientValues) == 0 {
return nil, errcode.ErrJWTAuthNotFound
}
meta := &Meta{
IDENTITY: md["authorization_identity"][0],
CLIENT: md["client"][0],

View File

@@ -1,12 +1,17 @@
package service
import (
"context"
"log"
"net"
"os"
"strconv"
"strings"
"net/http"
gwRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
@@ -25,9 +30,12 @@ type (
}
Options struct {
Addr string
Conf *conf.MicroServiceConf
EtcdClient *clientv3.Client
Addr string
EtcdClient *clientv3.Client
MsConf *conf.MicroServiceConf
GatewayConf *conf.GatewayConf
GatewayCtx context.Context
GatewayMux *gwRuntime.ServeMux
}
)
@@ -43,11 +51,12 @@ func (s *Service) Start() {
print.Info("[BSM - %s] Service Starting ...", vars.ServiceKey)
// register to etcd.
if s.Opts.Conf != nil && s.Opts.Conf.Enable {
if s.Opts.MsConf != nil && s.Opts.MsConf.Enable {
if s.Opts.EtcdClient == nil {
print.Error("[BSM Register] Etcd Client is nil.")
os.Exit(1)
}
print.Info("[BSM - %s] Registering Service to Etcd ...", vars.ServiceKey)
// get methods
methods := FoundGrpcMethods(s.GrpcSrv)
@@ -62,7 +71,7 @@ func (s *Service) Start() {
anonKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/"
register.SetAnonymous(anonKey, s.Opts.Conf.Anonymous)
register.SetAnonymous(anonKey, s.Opts.MsConf.Anonymous)
// service register lease
go register.ListenLeaseRespChan()
@@ -74,11 +83,29 @@ func (s *Service) Start() {
panic(err)
}
print.Success("[BSM - %s] Service Grpc Register & Runing Success!", vars.ServiceKey)
if err := s.GrpcSrv.Serve(tcpListen); err != nil {
panic(err)
go func() {
if err := s.GrpcSrv.Serve(tcpListen); err != nil {
panic(err)
}
}()
print.Success("[BSM - %s] Grpc %s Runing Success !", vars.ServiceKey, s.Opts.Addr)
if s.Opts.GatewayConf != nil && s.Opts.GatewayConf.Enable {
addr := Addr("0.0.0.0", s.Opts.GatewayConf.Port)
go s.Gateway(s.Opts.Addr, addr)
print.Success("[BSM - %s] Http %s Runing Success!", vars.ServiceKey, addr)
}
select {}
}
func (s *Service) Gateway(grpcAddr string, httpAddr string) {
// 1. 定义一个context
_, cancel := context.WithCancel(s.Opts.GatewayCtx)
defer cancel()
http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
}
func (s *Service) Stop() {