add grpc server support

This commit is contained in:
yanghao05
2023-05-06 15:29:16 +08:00
parent 3a9a1a6eeb
commit 4964b59b2c
9 changed files with 156 additions and 35 deletions

30
providers/grpcs/config.go Normal file
View File

@@ -0,0 +1,30 @@
package grpcs
import (
"fmt"
)
const DefaultPrefix = "Grpc"
type Config struct {
Host *string
Port uint
Tls *Tls
}
type Tls struct {
CA string
Cert string
Key string
}
func (h *Config) Address() string {
if h.Host == nil {
return h.PortString()
}
return fmt.Sprintf("%s:%d", *h.Host, h.Port)
}
func (h *Config) PortString() string {
return fmt.Sprintf(":%d", h.Port)
}

76
providers/grpcs/grpcs.go Normal file
View File

@@ -0,0 +1,76 @@
package grpcs
import (
"net"
"github.com/pkg/errors"
"github.com/rogeecn/atom/container"
"github.com/rogeecn/atom/providers/log"
"github.com/rogeecn/atom/utils/opt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/reflection"
)
func DefaultProvider() container.ProviderContainer {
return container.ProviderContainer{
Provider: Provide,
Options: []opt.Option{
opt.Prefix(DefaultPrefix),
},
}
}
// 给注入启动调用使用
type ServerService interface {
Name() string
Register(*grpc.Server)
}
type Grpc struct {
server *grpc.Server
config *Config
}
func Provide(opts ...opt.Option) error {
o := opt.New(opts...)
var config Config
if err := o.UnmarshalConfig(&config); err != nil {
log.Fatal(err)
}
return container.Container.Provide(func() (*Grpc, error) {
serverOptions := []grpc.ServerOption{}
// tls
if config.Tls != nil {
tlsConfig, err := credentials.NewServerTLSFromFile(config.Tls.Cert, config.Tls.Key)
if err != nil {
return nil, errors.Wrap(err, "Failed to create tls credential")
}
serverOptions = append(serverOptions, grpc.Creds(tlsConfig))
}
return &Grpc{
server: grpc.NewServer(serverOptions...),
config: &config,
}, nil
}, o.DiOptions()...)
}
func (g *Grpc) Serve() error {
ld, err := net.Listen("tcp", g.config.Address())
if err != nil {
return errors.Wrapf(err, "bind address failed: %s", g.config.Address())
}
log.Infof("grpc server listen on %s", g.config.Address())
reflection.Register(g.server)
return g.server.Serve(ld)
}
func (g *Grpc) RegisterService(name string, f func(*grpc.Server)) {
log.Debug("register service:", name)
f(g.server)
}

View File

@@ -4,7 +4,7 @@ import (
"fmt"
)
const ConfigPrefix = "Http"
const DefaultPrefix = "Http"
type Config struct {
Static *string

View File

@@ -1,33 +0,0 @@
package http
import (
"log"
"github.com/spf13/viper"
)
const DefaultPrefix = "Http"
func AutoLoadConfig() *Config {
return LoadConfig("")
}
func LoadConfig(file string) *Config {
if file == "" {
file = "config.toml"
}
v := viper.NewWithOptions(viper.KeyDelimiter("_"))
v.AutomaticEnv()
v.SetConfigFile(file)
if err := v.ReadInConfig(); err != nil {
log.Fatal(err)
}
var config Config
if err := v.UnmarshalKey(DefaultPrefix, &config); err != nil {
log.Fatal(err)
}
return &config
}