server

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2021 License: MIT Imports: 38 Imported by: 1

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

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

func ListenAndServe(services ...Service) error

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

func ListenAndServeContext(ctx context.Context, services ...Service) error

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

type HTTPInterceptor = func(http.Handler) http.Handler

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

func APIPrefix(prefix string) Option

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 Address added in v0.1.0

func Address(addr string) Option

Address is an option to set address. Default address is :8000

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 CORS added in v0.1.1

func CORS(allowCredential bool, headers, methods, origins []string) Option

CORS is an option allows users to enable CORS on the server.

func FromConfig added in v0.1.0

func FromConfig(conf Config) Option

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

func Handler(path string, h http.Handler, methods ...string) Option

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

func HandlerFunc(path string, h func(http.ResponseWriter, *http.Request), methods ...string) Option

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

func HealthCheck(path string, srv health.Server) Option

HealthCheck is an option allows user to provide a custom health check server.

func HealthChecks

func HealthChecks(checkers map[string]health.Checker) Option

HealthChecks is an option allows user to provide custom health checkers using default health check server.

func JWT added in v0.1.6

func JWT(secret string) Option

JWT is an option allows user to use jwt authenticator for authentication.

func Listener added in v0.1.3

func Listener(lis net.Listener) Option

Listener is an option allows server to be served on an existing listener.

func Logger

func Logger(logger log.Logger) Option

Logger is an option allows user to add a custom logger into the server.

func Metrics added in v0.1.4

func Metrics(path string) Option

Metrics is an option to register standard Prometheus metrics for HTTP. Default path is /internal/metrics.

func NotFoundHandler added in v0.1.8

func NotFoundHandler(h http.Handler) Option

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 PProf added in v0.1.1

func PProf(pathPrefix string) Option

PProf is an option allows user to enable Go profiler.

func PrefixHandler added in v0.1.8

func PrefixHandler(path string, h http.Handler, methods ...string) Option

PrefixHandler is an option to quickly define a prefix HTTP handler. For more options, please use HTTPHandlerX.

func Recovery added in v0.1.1

func Recovery(handler func(context.Context, interface{}) error) Option

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

func RoutesPrioritization(enable bool) Option

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

func ShutdownHook(path string) Option

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

func ShutdownTimeout(t time.Duration) Option

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

func TLS(key, cert string) Option

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 Timeout

func Timeout(read, write time.Duration) Option

Timeout is an option to override default read/write timeout.

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.

func Web added in v0.0.7

func Web(pathPrefix, dir, index string) Option

Web is an option to allows user to serve Web/Single Page Application along with API Gateway and gRPC. API Gateway must be served in a different path prefix with the web path prefix.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server holds the configuration options for the server instance.

func New

func New(ops ...Option) *Server

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) Address added in v0.1.0

func (server *Server) Address() string

Address return address that the server is listening.

func (*Server) ListenAndServe

func (server *Server) ListenAndServe(services ...Service) error

ListenAndServe call ListenAndServeContext with background context.

func (*Server) ListenAndServeContext

func (server *Server) ListenAndServeContext(ctx context.Context, services ...Service) error

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.

func (*Server) Shutdown added in v0.2.0

func (server *Server) Shutdown(ctx context.Context)

Shutdown shutdown the server gracefully.

func (*Server) With added in v0.1.0

func (server *Server) With(opts ...Option) *Server

With allows user to add more options to the server after created.

type Service

type Service interface {
	Register(srv *grpc.Server)
}

Service implements a registration interface for services to attach themselves to the grpc.Server. If the services support gRPC gateway, they must also implement the EndpointService interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL