Documentation ¶
Overview ¶
Package server provides a convenient way to create or start a new server that serves both gRPC and HTTP over 1 single port with default useful APIs for authentication, health check, metrics,...
Index ¶
- func CorrelationIDStreamInterceptor() grpc.StreamServerInterceptor
- func CorrelationIDUnaryInterceptor() grpc.UnaryServerInterceptor
- func DefaultHeaderMatcher() runtime.ServeMuxOption
- func GetAddressFromEnv(opts ...config.ReadOption) string
- func HeaderMatcher(keys []string) runtime.ServeMuxOption
- func ListenAndServe(services ...Service) error
- func ListenAndServeContext(ctx context.Context, services ...Service) error
- type Config
- type EndpointService
- type HTTPInterceptor
- type HandlerOptions
- func (r *HandlerOptions) Headers(headers ...string) *HandlerOptions
- func (r *HandlerOptions) Interceptors(interceptors ...HTTPInterceptor) *HandlerOptions
- func (r *HandlerOptions) Methods(methods ...string) *HandlerOptions
- func (r *HandlerOptions) Prefix() *HandlerOptions
- func (r *HandlerOptions) Queries(queries ...string) *HandlerOptions
- type Option
- func APIPrefix(prefix string) Option
- func Address(addr string) Option
- func AddressFromEnv(opts ...config.ReadOption) Option
- func Auth(f auth.Authenticator) Option
- func CORS(allowCredential bool, headers, methods, origins []string) Option
- func FromConfig(conf Config) Option
- func FromEnv(configOpts ...config.ReadOption) Option
- func HTTPInterceptors(interceptors ...HTTPInterceptor) Option
- func Handler(path string, h http.Handler, methods ...string) Option
- func HandlerFunc(path string, h func(http.ResponseWriter, *http.Request), methods ...string) Option
- func HandlerWithOptions(path string, h http.Handler, hopt *HandlerOptions) Option
- func HealthCheck(path string, srv health.Server) Option
- func HealthChecks(checkers map[string]health.Checker) Option
- func JWT(secret string) Option
- func Listener(lis net.Listener) Option
- func Logger(logger log.Logger) Option
- func Metrics(path string) Option
- func NotFoundHandler(h http.Handler) Option
- func Options(serverOpts ...grpc.ServerOption) Option
- func PProf(pathPrefix string) Option
- func PrefixHandler(path string, h http.Handler, methods ...string) Option
- func Recovery(handler func(context.Context, interface{}) error) Option
- func RoutesPrioritization(enable bool) Option
- func ServeMuxOptions(muxOpts ...runtime.ServeMuxOption) Option
- func ShutdownHook(path string) Option
- func ShutdownTimeout(t time.Duration) Option
- func StreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option
- func StreamTracing(tracer opentracing.Tracer) Option
- func TLS(key, cert string) Option
- func Timeout(read, write time.Duration) Option
- func Tracing(tracer opentracing.Tracer) Option
- func UnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option
- func Web(pathPrefix, dir, index string) Option
- type Server
- type Service
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CorrelationIDStreamInterceptor ¶ added in v0.2.0
func CorrelationIDStreamInterceptor() grpc.StreamServerInterceptor
CorrelationIDStreamInterceptor returns a grpc.StreamServerInterceptor that provides a context with correlation_id for tracing. It will try to looks for value of X-Correlation-ID or X-Request-ID in the metadata of the incoming request. If no value is provided, a new UUID will be generated.
func CorrelationIDUnaryInterceptor ¶ added in v0.2.0
func CorrelationIDUnaryInterceptor() grpc.UnaryServerInterceptor
CorrelationIDUnaryInterceptor returns a grpc.UnaryServerInterceptor that provides a context with correlation_id for tracing. It will try to looks for value of X-Correlation-ID or X-Request-ID in the metadata of the incoming request. If no value is provided, a new UUID will be generated.
func DefaultHeaderMatcher ¶
func DefaultHeaderMatcher() runtime.ServeMuxOption
DefaultHeaderMatcher is an ServerMuxOption that forward header keys X-Request-Id, X-Correlation-ID, Api-Key to gRPC Context.
func GetAddressFromEnv ¶ added in v0.2.0
func GetAddressFromEnv(opts ...config.ReadOption) string
GetAddressFromEnv returns address from configured environment variables: PORT or ADDRESS. This function prioritizes PORT over ADDRESS. If non of the variables is configured, return default address.
func HeaderMatcher ¶
func HeaderMatcher(keys []string) runtime.ServeMuxOption
HeaderMatcher is an ServeMuxOption for matcher header for passing a set of non IANA headers to gRPC context without a need to prefix them with Grpc-Metadata.
func ListenAndServe ¶
ListenAndServe create a new server base on environment configuration (see server.Config) and serve the services with background context. See server.ListenAndServe for detail document.
Example ¶
package main import ( "github.com/pthethanh/micro/server" ) func main() { if err := server.ListenAndServe( /*services ...Service*/ ); err != nil { panic(err) } }
Output:
func ListenAndServeContext ¶
ListenAndServeContext create a new server base on environment configuration (see server.Config) and serve the services with the given context. See server.ListenAndServeContext for detail document.
Example ¶
package main import ( "context" "github.com/pthethanh/micro/server" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := server.ListenAndServeContext(ctx /*, services ...Service*/); err != nil { panic(err) } }
Output:
Types ¶
type Config ¶
type Config struct { // Name is name of the service. Name string `envconfig:"NAME" default:"micro"` // Address is the address of the service in form of host:port. // If PORT environment variable is configured, it will be prioritized over ADDRESS. Address string `envconfig:"ADDRESS" default:":8000"` // TLSCertFile is path to the TLS certificate file. TLSCertFile string `envconfig:"TLS_CERT_FILE"` // TLSKeyFile is the path to the TLS key file. TLSKeyFile string `envconfig:"TLS_KEY_FILE"` // HealthCheckPath is API path for the health check. HealthCheckPath string `envconfig:"HEALTH_CHECK_PATH" default:"/internal/health"` // ReadTimeout is read timeout of both gRPC and HTTP server. ReadTimeout time.Duration `envconfig:"READ_TIMEOUT" default:"30s"` // WriteTimeout is write timeout of both gRPC and HTTP server. WriteTimeout time.Duration `envconfig:"WRITE_TIMEOUT" default:"30s"` //ShutdownTimeout is timeout for shutting down the server. ShutdownTimeout time.Duration `envconfig:"SHUTDOWN_TIMEOUT" default:"30s"` // APIPrefix is path prefix that gRPC API Gateway is routed to. APIPrefix string `envconfig:"API_PREFIX" default:"/api/"` // Web options WebDir string `envconfig:"WEB_DIR"` WebIndex string `envconfig:"WEB_INDEX" default:"index.html"` WebPrefix string `envconfig:"WEB_PREFIX" default:"/"` // JWTSecret is a short way to enable JWT Authentictor with the secret. JWTSecret string `envconfig:"JWT_SECRET"` // ContextLogger is an option to enable context logger with request-id. ContextLogger bool `envconfig:"CONTEXT_LOGGER" default:"true"` // Recovery is a short way to enable recovery interceptors for both unary and stream handlers. Recovery bool `envconfig:"RECOVERY" default:"true"` // CORS options CORSAllowedHeaders []string `envconfig:"CORS_ALLOWED_HEADERS"` CORSAllowedMethods []string `envconfig:"CORS_ALLOWED_METHODS"` CORSAllowedOrigins []string `envconfig:"CORS_ALLOWED_ORIGINS"` CORSAllowedCredential bool `envconfig:"CORS_ALLOWED_CREDENTIAL" default:"false"` // PProf options PProf bool `envconfig:"PPROF" default:"false"` PProfPrefix string `envconfig:"PPROF_PREFIX"` // Metrics enable/disable standard metrics Metrics bool `envconfig:"METRICS" default:"true"` // MetricsPath is API path for Prometheus metrics. MetricsPath string `envconfig:"METRICS_PATH" default:"/internal/metrics"` RoutesPrioritization bool `envconfig:"ROUTES_PRIORITIZATION" default:"true"` ShutdownHook string `envconfig:"SHUTDOWN_HOOK"` }
Config is a common configuration of a default server.
func ReadConfigFromEnv ¶ added in v0.1.7
func ReadConfigFromEnv(opts ...config.ReadOption) Config
ReadConfigFromEnv read the server configuration from environment variables.
type EndpointService ¶
type EndpointService interface {
RegisterWithEndpoint(ctx context.Context, mux *runtime.ServeMux, addr string, opts []grpc.DialOption)
}
EndpointService implement an endpoint registration interface for service to attach their endpoints to gRPC gateway.
type HTTPInterceptor ¶ added in v0.1.8
HTTPInterceptor is an interceptor/middleware func.
type HandlerOptions ¶ added in v0.1.8
type HandlerOptions struct {
// contains filtered or unexported fields
}
HandlerOptions hold information of a HTTP handler options.
func NewHandlerOptions ¶ added in v0.1.8
func NewHandlerOptions() *HandlerOptions
NewHandlerOptions return new empty HTTP options.
func (*HandlerOptions) Headers ¶ added in v0.1.8
func (r *HandlerOptions) Headers(headers ...string) *HandlerOptions
Headers adds a matcher for request header values. It accepts a sequence of key/value pairs to be matched.
func (*HandlerOptions) Interceptors ¶ added in v0.1.8
func (r *HandlerOptions) Interceptors(interceptors ...HTTPInterceptor) *HandlerOptions
Interceptors adds interceptors into the handler.
func (*HandlerOptions) Methods ¶ added in v0.1.8
func (r *HandlerOptions) Methods(methods ...string) *HandlerOptions
Methods adds a matcher for HTTP methods. It accepts a sequence of one or more methods to be matched.
func (*HandlerOptions) Prefix ¶ added in v0.1.8
func (r *HandlerOptions) Prefix() *HandlerOptions
Prefix mark that the HTTP handler is a prefix handler.
func (*HandlerOptions) Queries ¶ added in v0.1.8
func (r *HandlerOptions) Queries(queries ...string) *HandlerOptions
Queries adds a matcher for URL query values. It accepts a sequence of key/value pairs. Values may define variables.
type Option ¶
type Option func(*Server)
Option is a configuration option.
func APIPrefix ¶ added in v0.0.7
APIPrefix is an option allows user to route only the specified path prefix to gRPC Gateway. This option is used mostly when you serve both gRPC APIs along with other internal HTTP APIs. The default prefix is /, which will route all paths to gRPC Gateway.
func AddressFromEnv ¶ added in v0.0.2
func AddressFromEnv(opts ...config.ReadOption) Option
AddressFromEnv is an option allows user to set address using environment configuration. It looks for PORT and then ADDRESS variables. This option is mostly used for cloud environment like Heroku where the port is randomly set.
func Auth ¶ added in v0.0.6
func Auth(f auth.Authenticator) Option
Auth is an option allows user to use an authenticator for authentication. Find more about authenticators in auth package.
func FromConfig ¶ added in v0.1.0
FromConfig is an option to create a new server from an existing config.
func FromEnv ¶ added in v0.0.8
func FromEnv(configOpts ...config.ReadOption) Option
FromEnv is an option to create a new server from environment variables configuration. See Config for the available options.
func HTTPInterceptors ¶ added in v0.1.1
func HTTPInterceptors(interceptors ...HTTPInterceptor) Option
HTTPInterceptors is an option allows user to set additional interceptors to the root HTTP handler. If interceptors are applied to gRPC, it is required that the interceptors don't hijack the response writer, otherwise panic "Hijack not supported" will be thrown.
func Handler ¶ added in v0.1.8
Handler is an option allows user to add additional HTTP handlers. Longer patterns take precedence over shorter ones by default, use RoutesPrioritization option to disable this rule. See github.com/gorilla/mux for defining path with variables/patterns.
For more options, use HTTPHandlerX.
func HandlerFunc ¶ added in v0.1.8
HandlerFunc is an option similar to HTTPHandler, but for http.HandlerFunc.
func HandlerWithOptions ¶ added in v0.1.8
func HandlerWithOptions(path string, h http.Handler, hopt *HandlerOptions) Option
HandlerWithOptions is an option to define full options such as method, query, header matchers and interceptors for a HTTP handler. Longer patterns take precedence over shorter ones by default, use RoutesPrioritization option to disable this rule. See github.com/gorilla/mux for defining path with variables/patterns.
func HealthCheck ¶ added in v0.1.8
HealthCheck is an option allows user to provide a custom health check server.
func HealthChecks ¶
HealthChecks is an option allows user to provide custom health checkers using default health check server.
func JWT ¶ added in v0.1.6
JWT is an option allows user to use jwt authenticator for authentication.
func Listener ¶ added in v0.1.3
Listener is an option allows server to be served on an existing listener.
func Metrics ¶ added in v0.1.4
Metrics is an option to register standard Prometheus metrics for HTTP. Default path is /internal/metrics.
func NotFoundHandler ¶ added in v0.1.8
NotFoundHandler is an option to provide a custom not found HTTP Handler.
func Options ¶
func Options(serverOpts ...grpc.ServerOption) Option
Options is an option allows user to add additional grpc.ServerOption.
func PrefixHandler ¶ added in v0.1.8
PrefixHandler is an option to quickly define a prefix HTTP handler. For more options, please use HTTPHandlerX.
func Recovery ¶ added in v0.1.1
Recovery is an option allows user to add an ability to recover a handler/API from a panic. This applies for both unary and stream handlers/APIs. If the provided error handler is nil, a default error handler will be used.
func RoutesPrioritization ¶ added in v0.1.8
RoutesPrioritization enable/disable the routes prioritization.
func ServeMuxOptions ¶
func ServeMuxOptions(muxOpts ...runtime.ServeMuxOption) Option
ServeMuxOptions is an option allows user to add additional ServeMuxOption.
func ShutdownHook ¶ added in v0.2.0
ShutdownHook expose an API for shutdown the server remotely.
WARNING: this is an experiment API and it should be enabled only in development mode for live reload.
func ShutdownTimeout ¶ added in v0.1.7
ShutdownTimeout is an option to override default shutdown timeout of server. Set to -1 for no timeout.
func StreamInterceptors ¶
func StreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option
StreamInterceptors is an option allows user to add additional stream interceptors to the server.
func StreamTracing ¶ added in v0.1.9
func StreamTracing(tracer opentracing.Tracer) Option
StreamTracing is an option to enable tracing on stream requests.
func TLS ¶
TLS is an option allows user to add TLS for transport security to the server. Note that host name in ADDRESS must be configured accordingly. Otherwise, you might encounter TLS handshake error. TIP: for local testing, take a look at https://github.com/FiloSottile/mkcert.
func Tracing ¶ added in v0.1.9
func Tracing(tracer opentracing.Tracer) Option
Tracing is an option to enable tracing on unary requests.
func UnaryInterceptors ¶
func UnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option
UnaryInterceptors is an option allows user to add additional unary interceptors to the server.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server holds the configuration options for the server instance.
func New ¶
New return new server with the given options. If address is not set, default address ":8000" will be used.
Example (FromEnvironmentVariables) ¶
package main import ( "github.com/pthethanh/micro/log" "github.com/pthethanh/micro/server" ) func main() { srv := server.New(server.FromEnv()) if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil { log.Panic(err) } }
Output:
Example (WithExternalInterceptors) ¶
package main import ( "github.com/pthethanh/micro/server" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/tracing" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/tags" grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus" ) func main() { srv := server.New( server.FromEnv(), server.StreamInterceptors( tags.StreamServerInterceptor(), tracing.StreamServerInterceptor(), grpc_prometheus.StreamServerInterceptor, recovery.StreamServerInterceptor(), ), server.UnaryInterceptors( tags.UnaryServerInterceptor(), tracing.UnaryServerInterceptor(), grpc_prometheus.UnaryServerInterceptor, recovery.UnaryServerInterceptor(), ), ) if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil { panic(err) } }
Output:
Example (WithInternalHTTPAPI) ¶
package main import ( "net/http" "github.com/pthethanh/micro/server" ) func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("doc")) }) srv := server.New( server.FromEnv(), server.Handler("/doc", h), ) if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil { panic(err) } }
Output:
Example (WithOptions) ¶
package main import ( "github.com/pthethanh/micro/log" "github.com/pthethanh/micro/server" ) func main() { srv := server.New( server.Address(":8080"), server.JWT("secret"), server.Logger(log.Fields("service", "micro")), ) if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil { panic(err) } }
Output:
Example (WithSinglePageApplication) ¶
package main import ( "github.com/pthethanh/micro/server" ) func main() { // See https://github.com/pthethanh/micro/tree/master/examples/helloworld/web for a full runnable example. srv := server.New( server.Address(":8080"), // routes all calls to /api/ to gRPC Gateway handlers. server.APIPrefix("/api/"), // serve web at / server.Web("/", "public", "index.html"), ) if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil { panic(err) } }
Output:
func (*Server) ListenAndServe ¶
ListenAndServe call ListenAndServeContext with background context.
func (*Server) ListenAndServeContext ¶
ListenAndServeContext opens a tcp listener used by a grpc.Server and a HTTP server, and registers each Service with the grpc.Server. If the Service implements EndpointService its endpoints will be registered to the HTTP Server running on the same port. The server starts with default metrics and health endpoints. If the context is canceled or times out, the gRPC server will attempt a graceful shutdown.