server

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2020 License: MIT Imports: 25 Imported by: 1

Documentation

Overview

Package server provides a convenient way to start a new ready to use server with default HTTP API for readiness, liveness and Prometheus metrics.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultHeaderMatcher

func DefaultHeaderMatcher() runtime.ServeMuxOption

DefaultHeaderMatcher is an ServerMuxOption that forward header keys request-id, api-key to gRPC Context.

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 Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context) (context.Context, error)
}

Authenticator defines the interface to perform the actual authentication of the request. Implementations should fetch the required data from the context.Context object. GRPC specific data like `metadata` and `peer` is available on the context. Should return a new `context.Context` that is a child of `ctx` or `codes.Unauthenticated` when auth is lacking or `codes.PermissionDenied` when lacking permissions.

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.
	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"`

	// LivenessPath is API path for the liveness/health check API.
	LivenessPath string `envconfig:"LIVENESS_PATH" default:"/internal/liveness"`
	// ReadinessPath is API path for the readiness API.
	ReadinessPath string `envconfig:"READINESS_PATH" default:"/internal/readiness"`
	// MetricsPath is API path for Prometheus metrics.
	MetricsPath string `envconfig:"METRICS_PATH" default:"/internal/metrics"`

	// 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"`
	// APIPrefix is path prefix that gRPC API Gateway is routed to.
	APIPrefix string `envconfig:"API_PREFIX" default:"/"`
	// Web is a short config for serving web application.
	// The config format is: path-to-public-dir,index-file-name
	// Example: public,index.html
	Web []string `envconfig:"WEB"`

	// 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"`
}

Config is a common configuration of a default server. Mostly used by lazy guys via FromEnv().

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 endpoint to GRPC gateway

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 AddressFromEnv added in v0.0.2

func AddressFromEnv() 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

Auth is an option allows user to add an authenticator to the server.

func AuthJWT added in v0.0.8

func AuthJWT(secret string) Option

AuthJWT is an option allows user to add jwt authenticator to the server.

func FromEnv added in v0.0.8

func FromEnv(configOpts ...config.ReadOption) Option

FromEnv is an option allows user to load configuration from environment variables. See Config for the available options.

func HTTPHandler added in v0.0.5

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

HTTPHandler is an option allows user to add additional HTTP handlers. If you want to apply middlewares on the HTTP handlers, do it yourselves.

func HealthChecks

func HealthChecks(checks ...health.CheckFunc) Option

HealthChecks is an option allows user to set health check function.

func Logger

func Logger(logger log.Logger) Option

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

func MetricsPaths

func MetricsPaths(ready, live, metrics string) Option

MetricsPaths is an option allows user to override readiness, liveness and metrics path.

func Options

func Options(serverOpts ...grpc.ServerOption) Option

Options is an option allows user to add additional grpc.ServerOption.

func ServeMuxOptions

func ServeMuxOptions(muxOpts ...runtime.ServeMuxOption) Option

ServeMuxOptions is an option allows user to add additional ServeMuxOption.

func StreamInterceptors

func StreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option

StreamInterceptors is an option allows user to add additional stream interceptors to the server.

func TLS

func TLS(key, cert string) Option

TLS is an option allows user to add TLS for transport security to the server.

func Timeout

func Timeout(read, write time.Duration) Option

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

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(dir string, 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 different from root path / by using server.APIPrefix(prefix), otherwise a panic will be thrown.

type Server

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

Server holds the configuration options for the server instance.

func New

func New(addr string, ops ...Option) *Server

New return new server

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 (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.HTTPHandler("/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(":8080",
		server.AuthJWT("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(":8080",
		// routes all calls to /api/ to gRPC Gateway handler to avoid conlision with server.Web
		server.APIPrefix("/api/"),
		// serve SPA at /
		server.Web("public", "index.html"),
	)
	if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil {
		panic(err)
	}
}
Output:

func NewFromEnv

func NewFromEnv() *Server

NewFromEnv load configurations from environment and create a new server. Additional options can be added to the sever via Server.WithOptions(...). See Config for environment names.

Example
package main

import (
	"github.com/pthethanh/micro/server"
)

func main() {
	srv := server.NewFromEnv()
	if err := srv.ListenAndServe( /*services ...Service*/ ); err != nil {
		panic(err)
	}
}
Output:

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) WithOptions

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

WithOptions allows 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.

Jump to

Keyboard shortcuts

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