Documentation
¶
Index ¶
- func CreateGatewayMux() *runtime.ServeMux
- func DefaultHealthCheckers() map[string]HealthChecker
- func MountGatewayOnEcho(e *echo.Echo, gatewayMux *runtime.ServeMux, basePath string)
- func Start(port string, serviceRegistrar func(*grpc.Server), opts ...Option) error
- func StartH2C(port string, serviceRegistrar func(*grpc.Server), opts ...Option) error
- func StartSeparate(grpcPort, httpPort string, serviceRegistrar func(*grpc.Server), opts ...Option) error
- type HealthCheckResult
- type HealthChecker
- type HealthManager
- func (h *HealthManager) CheckHealth() map[string]HealthCheckResult
- func (h *HealthManager) GetOverallStatus() HealthStatus
- func (h *HealthManager) RegisterCheck(name string, checker HealthChecker)
- func (h *HealthManager) RegisterEchoHealthChecks(e *echo.Echo, basePath string)
- func (h *HealthManager) RemoveCheck(name string)
- func (h *HealthManager) SetEnabled(enabled bool)
- type HealthStatus
- type Option
- func WithCORS() Option
- func WithCORSConfig(corsConfig middleware.CORSConfig) Option
- func WithConnectionTimeouts(idle, age, grace time.Duration) Option
- func WithEchoConfigurer(fn func(*echo.Echo)) Option
- func WithGRPCConfigurer(fn func(*grpc.Server)) Option
- func WithGRPCPort(port string) Option
- func WithGatewayBasePath(path string) Option
- func WithGatewayRegistrar(fn func(mux *runtime.ServeMux)) Option
- func WithH2CMode() Option
- func WithHTTPPort(port string) Option
- func WithHealthCheck() Option
- func WithHealthPath(path string) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithMaxConnectionAge(d time.Duration) Option
- func WithMaxConnectionAgeGrace(d time.Duration) Option
- func WithMaxConnectionIdle(d time.Duration) Option
- func WithMiddleware(mw ...echo.MiddlewareFunc) Option
- func WithOTelConfig(cfg *otel.Config) Option
- func WithRateLimit(rps float64) Option
- func WithReadTimeout(d time.Duration) Option
- func WithReflection() Option
- func WithSeparateMode(grpcPort, httpPort string) Option
- func WithServiceRegistrar(fn func(*grpc.Server)) Option
- func WithShutdownHandler(fn func() error) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithWriteTimeout(d time.Duration) Option
- func WithoutHealthCheck() Option
- func WithoutReflection() Option
- type Server
- type ServerMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CreateGatewayMux ¶
CreateGatewayMux creates a new gateway mux with standard configuration
func DefaultHealthCheckers ¶
func DefaultHealthCheckers() map[string]HealthChecker
DefaultHealthCheckers returns a set of default health checkers
func MountGatewayOnEcho ¶
MountGatewayOnEcho mounts a gRPC gateway mux onto Echo under a base path. The base path is stripped before the request reaches the mux, so the mux sees proto http-rule paths verbatim (e.g. "/users", not "/api/v1/users").
Types ¶
type HealthCheckResult ¶
type HealthCheckResult struct {
Status HealthStatus `json:"status"`
Timestamp time.Time `json:"timestamp"`
Duration time.Duration `json:"duration"`
Details map[string]interface{} `json:"details,omitempty"`
Error string `json:"error,omitempty"`
}
HealthCheckResult represents the result of a health check
type HealthChecker ¶
type HealthChecker func() HealthCheckResult
HealthChecker defines the interface for health check functions
type HealthManager ¶
type HealthManager struct {
// contains filtered or unexported fields
}
HealthManager manages health checks for the server
func NewHealthManager ¶
func NewHealthManager() *HealthManager
NewHealthManager creates a new health manager
func (*HealthManager) CheckHealth ¶
func (h *HealthManager) CheckHealth() map[string]HealthCheckResult
CheckHealth runs all registered health checks
func (*HealthManager) GetOverallStatus ¶
func (h *HealthManager) GetOverallStatus() HealthStatus
GetOverallStatus returns the overall health status.
func (*HealthManager) RegisterCheck ¶
func (h *HealthManager) RegisterCheck(name string, checker HealthChecker)
RegisterCheck registers a health check with the given name
Example ¶
package main
import (
"fmt"
grpcserver "github.com/jasoet/pkg/v3/grpc"
)
func main() {
hm := grpcserver.NewHealthManager()
hm.RegisterCheck("database", func() grpcserver.HealthCheckResult {
return grpcserver.HealthCheckResult{Status: grpcserver.HealthStatusUp}
})
fmt.Println(hm.GetOverallStatus())
}
Output: UP
func (*HealthManager) RegisterEchoHealthChecks ¶
func (h *HealthManager) RegisterEchoHealthChecks(e *echo.Echo, basePath string)
RegisterEchoHealthChecks registers health check endpoints with Echo
func (*HealthManager) RemoveCheck ¶
func (h *HealthManager) RemoveCheck(name string)
RemoveCheck removes a health check
func (*HealthManager) SetEnabled ¶
func (h *HealthManager) SetEnabled(enabled bool)
SetEnabled enables or disables health checks
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the status of a health check
const ( // HealthStatusUp indicates the service is healthy HealthStatusUp HealthStatus = "UP" // HealthStatusDown indicates the service is unhealthy HealthStatusDown HealthStatus = "DOWN" // HealthStatusUnknown indicates the health status is unknown HealthStatusUnknown HealthStatus = "UNKNOWN" )
type Option ¶
type Option func(*config)
Option is a functional option for configuring the server
func WithCORS ¶
func WithCORS() Option
WithCORS enables CORS middleware with default (wildcard) configuration
func WithCORSConfig ¶
func WithCORSConfig(corsConfig middleware.CORSConfig) Option
WithCORSConfig enables CORS middleware with a custom configuration, replacing the default wildcard policy.
func WithConnectionTimeouts ¶
WithConnectionTimeouts sets all gRPC connection timeout values
func WithEchoConfigurer ¶
WithEchoConfigurer sets the function to configure the Echo HTTP server
func WithGRPCConfigurer ¶
WithGRPCConfigurer sets the function to configure the gRPC server
func WithGatewayBasePath ¶
WithGatewayBasePath sets the base path for gRPC gateway routes
func WithGatewayRegistrar ¶
WithGatewayRegistrar sets the function to register handlers on the gRPC gateway mux — typically closures around generated code such as pb.RegisterXxxHandlerServer(ctx, mux, conn). It is invoked during server start after the gateway mux is created and before it is mounted on Echo. The mounted gateway only serves what is registered through this option.
Example ¶
ExampleWithGatewayRegistrar demonstrates registering handlers on the gRPC gateway mux. It is compile-only: Start blocks until shutdown, so it is not called here.
package main
import (
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
grpcserver "github.com/jasoet/pkg/v3/grpc"
)
func main() {
server, err := grpcserver.New(
grpcserver.WithH2CMode(),
grpcserver.WithGRPCPort("8080"),
grpcserver.WithServiceRegistrar(func(s *grpc.Server) {
// pb.RegisterYourServiceServer(s, yourService)
}),
// The gateway mounted under the base path (default /api/v1) only
// serves what is registered here — typically generated code:
// pb.RegisterYourServiceHandlerServer(ctx, mux, conn)
// The mount strips the base path, so patterns are proto http-rule
// style ("/ping" here is served at /api/v1/ping):
grpcserver.WithGatewayRegistrar(func(mux *runtime.ServeMux) {
_ = mux.HandlePath(http.MethodGet, "/ping",
func(w http.ResponseWriter, _ *http.Request, _ map[string]string) {
_, _ = w.Write([]byte("pong"))
})
}),
)
if err != nil {
panic(err)
}
// server.Start() blocks serving until Stop is called; omitted here.
_ = server
}
Output:
func WithH2CMode ¶
func WithH2CMode() Option
WithH2CMode sets the server to H2C mode (gRPC and HTTP on same port)
func WithHTTPPort ¶
WithHTTPPort sets the HTTP gateway port (only used in SeparateMode)
func WithHealthPath ¶
WithHealthPath sets the health check base path
func WithIdleTimeout ¶
WithIdleTimeout sets the HTTP server idle timeout
func WithMaxConnectionAge ¶
WithMaxConnectionAge sets the maximum connection age for gRPC
func WithMaxConnectionAgeGrace ¶
WithMaxConnectionAgeGrace sets the connection age grace period for gRPC
func WithMaxConnectionIdle ¶
WithMaxConnectionIdle sets the maximum connection idle time for gRPC
func WithMiddleware ¶
func WithMiddleware(mw ...echo.MiddlewareFunc) Option
WithMiddleware adds custom Echo middleware
func WithOTelConfig ¶
WithOTelConfig sets the OpenTelemetry configuration for traces, metrics, and logs
func WithRateLimit ¶
WithRateLimit enables rate limiting with the specified requests per second
func WithReadTimeout ¶
WithReadTimeout sets the HTTP server read timeout
func WithSeparateMode ¶
WithSeparateMode sets the server to separate mode with different ports for gRPC and HTTP
func WithServiceRegistrar ¶
WithServiceRegistrar sets the function to register gRPC services
func WithShutdownHandler ¶
WithShutdownHandler sets a custom shutdown handler
func WithShutdownTimeout ¶
WithShutdownTimeout sets the graceful shutdown timeout
func WithWriteTimeout ¶
WithWriteTimeout sets the HTTP server write timeout
func WithoutHealthCheck ¶
func WithoutHealthCheck() Option
WithoutHealthCheck disables health check endpoints
func WithoutReflection ¶
func WithoutReflection() Option
WithoutReflection disables gRPC server reflection
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents the gRPC server and gateway
func New ¶
New creates a new server instance with the given options
Example ¶
ExampleNew demonstrates creating a server with the options API. It is compile-only: Start blocks until shutdown, so it is not called here.
package main
import (
"google.golang.org/grpc"
grpcserver "github.com/jasoet/pkg/v3/grpc"
)
func main() {
server, err := grpcserver.New(
grpcserver.WithH2CMode(),
grpcserver.WithGRPCPort("8080"),
grpcserver.WithServiceRegistrar(func(s *grpc.Server) {
// Register your gRPC services, e.g.:
// pb.RegisterYourServiceServer(s, yourService)
}),
)
if err != nil {
panic(err)
}
// server.Start() blocks serving until Stop is called; omitted here.
_ = server
}
Output:
func (*Server) GetGRPCServer ¶
GetGRPCServer returns the underlying gRPC server. It returns nil after Stop until the next Start rebuilds the server.
func (*Server) GetHealthManager ¶
func (s *Server) GetHealthManager() *HealthManager
GetHealthManager returns the health manager
type ServerMode ¶
type ServerMode string
ServerMode defines the server operation mode
const ( // SeparateMode runs gRPC and HTTP servers on separate ports SeparateMode ServerMode = "separate" // H2CMode runs both gRPC and HTTP on a single port using HTTP/2 cleartext H2CMode ServerMode = "h2c" )