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 ¶
- func DefaultHeaderMatcher() runtime.ServeMuxOption
- func HeaderMatcher(keys []string) runtime.ServeMuxOption
- func ListenAndServe(services ...Service) error
- func ListenAndServeContext(ctx context.Context, services ...Service) error
- type Authenticator
- type Config
- type EndpointService
- type Option
- func APIPrefix(prefix string) Option
- func AddressFromEnv() Option
- func Auth(f auth.AuthenticatorFunc) Option
- func AuthJWT(secret string) Option
- func FromEnv(configOpts ...config.ReadOption) Option
- func HTTPHandler(path string, h http.Handler) Option
- func HealthChecks(checks ...health.CheckFunc) Option
- func Logger(logger log.Logger) Option
- func MetricsPaths(ready, live, metrics string) Option
- func Options(serverOpts ...grpc.ServerOption) Option
- func ServeMuxOptions(muxOpts ...runtime.ServeMuxOption) Option
- func StreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option
- func TLS(key, cert string) Option
- func Timeout(read, write time.Duration) Option
- func UnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option
- func Web(dir string, index string) Option
- type Server
- type Service
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 ¶
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 Authenticator ¶
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
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
func Auth(f auth.AuthenticatorFunc) Option
Auth is an option allows user to add an authenticator to the server.
func AuthJWT ¶ added in v0.0.8
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
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 ¶
HealthChecks is an option allows user to set health check function.
func MetricsPaths ¶
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 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
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 ¶
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.
func (*Server) WithOptions ¶
WithOptions allows add more options to the server after created.