generated from pkg/go-template
46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package rpc
|
|
|
|
import (
|
|
_ "embed"
|
|
"fmt"
|
|
"git.icechen.cn/monorepo/backend/pkg/config"
|
|
"google.golang.org/grpc"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// GetServiceConnByEnv 通过环境变量获取服务的连接
|
|
func GetServiceConnByEnv(serviceName string) *grpc.ClientConn {
|
|
target := os.Getenv(strings.ToUpper("SERVICE_" + serviceName))
|
|
return getConn(target)
|
|
}
|
|
|
|
// GetServiceConn 获取服务的连接
|
|
func GetServiceConn(serviceName string) *grpc.ClientConn {
|
|
target := "dns:///service-" + serviceName + ":80"
|
|
if config.IsTest() {
|
|
target = "dns:///service-" + serviceName + "-test:80"
|
|
}
|
|
return getConn(target)
|
|
}
|
|
|
|
// GetServiceConnWithNamespace 获取跨项目的服务的连接
|
|
func GetServiceConnWithNamespace(serviceName string, namespace string) *grpc.ClientConn {
|
|
serviceName = serviceName + "." + namespace
|
|
target := "dns:///service-" + serviceName + ":80"
|
|
if config.IsTest() {
|
|
target = "dns:///service-" + serviceName + "-test:80"
|
|
}
|
|
return getConn(target)
|
|
}
|
|
|
|
func getConn(target string, opts ...grpc.DialOption) *grpc.ClientConn {
|
|
opts = append(opts, grpc.WithInsecure())
|
|
cli, err := grpc.Dial(target, opts...)
|
|
if err != nil {
|
|
fmt.Println("target: " + target + " err: " + err.Error())
|
|
return nil
|
|
}
|
|
return cli
|
|
}
|