Documentation
¶
Index ¶
- Variables
- func LoadConfig(apiName, filePath, envPrefix string) (*viper.Viper, error)
- type CustomHTTPRoute
- type Server
- type ServerOption
- func WithAuth(auth grpc_auth.AuthFunc) ServerOption
- func WithAuthz(authorizers ...authorizer.Authorizer) ServerOption
- func WithCache(provider providers.CacheProvider) ServerOption
- func WithContextTagger(tagger providers.ContextTaggerProvider) ServerOption
- func WithCustomHTTPRoute(method, path string, handler runtime.HandlerFunc) ServerOption
- func WithDatabase(provider providers.DatabaseProvider) ServerOption
- func WithGatewayOpts(opts ...runtime.ServeMuxOption) ServerOption
- func WithGrpcHealthCheck(srv grpc_health_v1.HealthServer) ServerOption
- func WithLogger(provider providers.LoggingProvider) ServerOption
- func WithMetrics(metrics providers.MetricsProvider) ServerOption
- func WithRateLimit(rateLimit limiter.Limiter) ServerOption
- func WithStream(provider providers.StreamProvider) ServerOption
- func WithStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) ServerOption
- func WithUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) ServerOption
- type Service
- type ServiceRegistration
- type ServiceRegistrationConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ConfigDefaults = map[string]interface{}{ `api.port`: 8080, `logging.level`: `debug`, `logging.tags`: []string{`method`, `context_id`, `error`}, `logging.request_body`: false, `database.migrate`: true, `api.cors.enabled`: false, `api.cors.allowed_origins`: []string{`*`}, `api.cors.allowed_methods`: []string{`GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`, `PATCH`}, `api.cors.allowed_headers`: []string{`*`}, `api.cors.exposed_headers`: []string{`*`}, `api.cors.allow_credentials`: true, }
ConfigDefaults are the default values for the config file
Functions ¶
Types ¶
type CustomHTTPRoute ¶
type CustomHTTPRoute struct { // Method is the http method Method string // Path is the http path Path string // Handler is the http handler Handler runtime.HandlerFunc }
CustomHTTPRoute is a custom route that can be added to the rest-gateway
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a highly configurable grpc server with a built-in rest-gateway(grpc-gateway) The server supports the following features via ServerOptions: - Logging Interface (slog) - Metrics Interface (prometheus) - Database Interface (sqlite/mysql/postgres) - Cache Interface (redis) - Stream Interface (nats/redis) - Context Tags - Authentication (see github.com/autom8ter/protoc-gen-authenticate) - Authorization (see github.com/autom8ter/protoc-gen-authorize) - Rate Limiting (see github.com/autom8ter/protoc-gen-ratelimit)
func NewServer ¶
NewServer creates a new server with the given config and options
Example ¶
package main import ( "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "github.com/autom8ter/grpcx" echov1 "github.com/autom8ter/grpcx/gen/echo" "github.com/autom8ter/grpcx/providers/maptags" "github.com/autom8ter/grpcx/providers/prometheus" redis2 "github.com/autom8ter/grpcx/providers/redis" slog2 "github.com/autom8ter/grpcx/providers/slog" "github.com/autom8ter/grpcx/providers/sqlite" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() cfg, err := grpcx.LoadConfig("test-api", "", "TEST_API") if err != nil { panic(err) } cfg.Set("auth.username", "test") cfg.Set("auth.password", "test") srv, err := grpcx.NewServer( ctx, cfg, // Register Cache Provider grpcx.WithCache(redis2.InMemProvider), // Register Stream Provider grpcx.WithStream(redis2.InMemStreamProvider), // Register Context Tagger grpcx.WithContextTagger(maptags.Provider), // Register Logger grpcx.WithLogger(slog2.Provider), // Register Database grpcx.WithDatabase(sqlite.Provider), // Register Metrics grpcx.WithMetrics(prometheus.Provider), ) if err != nil { panic(err) } go func() { if err := srv.Serve(ctx, EchoService()); err != nil { panic(err) } }() conn, err := grpc.DialContext(ctx, fmt.Sprintf("localhost:%v", cfg.GetInt("api.port")), grpc.WithInsecure()) if err != nil { panic(err) } defer conn.Close() echoClient := echov1.NewEchoServiceClient(conn) ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "test:test") resp, err := echoClient.Echo(ctx, &echov1.EchoRequest{ Message: "hello", }) if err != nil { panic(err) } println(resp.Message) } type echoServer struct { echov1.UnimplementedEchoServiceServer } func (e *echoServer) Echo(ctx context.Context, req *echov1.EchoRequest) (*echov1.EchoResponse, error) { var meta = map[string]string{} md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, status.Error(codes.Unauthenticated, "no metadata found in context") } for k, v := range md { meta[k] = v[0] } return &echov1.EchoResponse{ Message: req.Message, ClientMetadata: meta, }, nil } // EchoService returns a ServiceRegistration that registers an echo service func EchoService() grpcx.ServiceRegistration { return grpcx.ServiceRegistration(func(ctx context.Context, cfg grpcx.ServiceRegistrationConfig) error { echov1.RegisterEchoServiceServer(cfg.GrpcServer, &echoServer{}) return nil }) }
func (*Server) Serve ¶
Serve registers the given services and starts the server. This function blocks until the server is shutdown. The server will shutdown when the context is canceled or an interrupt signal is received. The server will start grpc/rest-gateway servers on the port specified by the config key "api.port" The server will register a health check at /health and a readiness check at /ready The server will register a metrics endpoint at /metrics if the config key "metrics.prometheus" is true
type ServerOption ¶
type ServerOption func(opt *serverOpt)
ServerOption is a function that configures the server. All ServerOptions are optional.
func WithAuth ¶
func WithAuth(auth grpc_auth.AuthFunc) ServerOption
WithAuth adds an auth provider to the server (see github.com/autom8ter/protoc-gen-authenticate)
func WithAuthz ¶ added in v0.3.0
func WithAuthz(authorizers ...authorizer.Authorizer) ServerOption
WithAuthz adds the authorizers to the server (see github.com/autom8ter/protoc-gen-authorize)
func WithCache ¶
func WithCache(provider providers.CacheProvider) ServerOption
WithCache adds a cache provider
func WithContextTagger ¶
func WithContextTagger(tagger providers.ContextTaggerProvider) ServerOption
WithContextTagger adds a context tagger to the server
func WithCustomHTTPRoute ¶
func WithCustomHTTPRoute(method, path string, handler runtime.HandlerFunc) ServerOption
WithCustomHTTPRoute adds a custom http route to the rest-gateway
func WithDatabase ¶
func WithDatabase(provider providers.DatabaseProvider) ServerOption
WithDatabase adds a database provider
func WithGatewayOpts ¶
func WithGatewayOpts(opts ...runtime.ServeMuxOption) ServerOption
WithGatewayOpts adds options to the grpc gateway
func WithGrpcHealthCheck ¶ added in v0.8.0
func WithGrpcHealthCheck(srv grpc_health_v1.HealthServer) ServerOption
WithGrpcHealthCheck adds a grpc health check to the server
func WithLogger ¶
func WithLogger(provider providers.LoggingProvider) ServerOption
WithLogger adds a logging provider
func WithMetrics ¶
func WithMetrics(metrics providers.MetricsProvider) ServerOption
WithMetrics adds a metrics provider to the server
func WithRateLimit ¶
func WithRateLimit(rateLimit limiter.Limiter) ServerOption
WithRateLimit adds a rate limiter to the server (see protoc-gen-ratelimit)
func WithStream ¶
func WithStream(provider providers.StreamProvider) ServerOption
WithStream adds a stream provider
func WithStreamInterceptors ¶
func WithStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) ServerOption
WithStreamInterceptors adds interceptors to the grpc server
func WithUnaryInterceptors ¶
func WithUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) ServerOption
WithUnaryInterceptors adds unary interceptors to the server
type Service ¶
type Service interface { // Register registers a service with the server Register(ctx context.Context, cfg ServiceRegistrationConfig) error }
Service is a an interface that registers a service with the server
type ServiceRegistration ¶
type ServiceRegistration func(ctx context.Context, cfg ServiceRegistrationConfig) error
ServiceRegistration is a function that registers a service with the server
func (ServiceRegistration) Register ¶
func (s ServiceRegistration) Register(ctx context.Context, cfg ServiceRegistrationConfig) error
Register implements the Service interface