server

package
v0.16.8 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2021 License: Apache-2.0 Imports: 15 Imported by: 0

README

Server

Server Wrapper

You can package your gRPC server along with your REST gateway, health checks and any other http endpoints using server.NewServer:

s, err := server.NewServer(
    server.WithGrpcServer(grpcServer),
    server.WithHealthChecks(healthChecks),
    server.WithGateway(
        gateway.WithEndpointRegistration("/v1/", server_test.RegisterHelloHandlerFromEndpoint),
        gateway.WithServerAddress(grpcL.Addr().String()),
    ),
)
if err != nil {
    log.Fatal(err)
}
// serve it by passing in net.Listeners for the respective servers
if err := s.Serve(grpcListener, httpListener); err != nil {
    log.Fatal(err)
}

You can see a full example here.

Documentation

Overview

This code is derived from https://github.com/coredns/coredns

Example
// for real-world apps, these net.Listeners will be created from addresses passed in from args (flag or env or whatever)
grpcL, err := servertest.NewLocalListener()
if err != nil {
	log.Fatal(err)
}
httpL, err := servertest.NewLocalListener()
if err != nil {
	log.Fatal(err)
}

grpcServer := grpc.NewServer()
server_test.RegisterHelloServer(grpcServer, &server_test.HelloServerImpl{})

healthChecks := health.NewChecksHandler("healthz", "ready")
healthChecks.AddLiveness("grpc", func() error {
	_, err := grpc.Dial(grpcL.Addr().String(), grpc.WithInsecure())
	return err
})

s, err := server.NewServer(
	server.WithGrpcServer(grpcServer),
	server.WithHealthChecks(healthChecks),
	server.WithGateway(
		gateway.WithEndpointRegistration("/v1/", server_test.RegisterHelloHandlerFromEndpoint),
		gateway.WithServerAddress(grpcL.Addr().String()),
	),
)
if err != nil {
	log.Fatal(err)
}

// normally, this would be the end of your main.go implementation. For the sake of this exampleClient, we'll make a
// simple request for demonstration
go s.Serve(grpcL, httpL)
defer s.Stop()

// demonstrate making a gRPC request through the grpc server url
conn, err := grpc.Dial(grpcL.Addr().String(), grpc.WithInsecure())
if err != nil {
	log.Fatal(err)
}
defer conn.Close()
client := server_test.NewHelloClient(conn)
gResp, err := client.SayHello(context.Background(), &server_test.HelloRequest{Name: "exampleClient"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(gResp.Greeting)

// demonstrate making a health check against the http url
hResp, err := http.Get(fmt.Sprint("http://", httpL.Addr().String(), "/healthz"))
if err != nil {
	log.Fatal(err)
}
fmt.Println(hResp.StatusCode)

// demonstrate making a REST request against the http url
gwResp, err := http.Get(fmt.Sprint("http://", httpL.Addr().String(), "/v1/hello?name=exampleREST"))
if err != nil {
	log.Fatal(err)
}
respBytes, err := ioutil.ReadAll(gwResp.Body)
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(respBytes))
Output:

hello, exampleClient!
200
{"greeting":"hello, exampleREST!"}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInitializeTimeout is returned when an InitializerFunc takes too long to finish during Server.Serve
	ErrInitializeTimeout = errors.New("initialization timed out")
	// DefaultInitializerTimeout is the reasonable default amount of time one would expect initialization to take in the
	// worst case
	DefaultInitializerTimeout = time.Minute
)

Functions

func MetricsFlags

func MetricsFlags() (*string, *string)

func NewTLSClientConfig

func NewTLSClientConfig(caPath string) (*tls.Config, error)

NewTLSClientConfig returns a TLS config for a client connection If caPath is empty, system CAs will be used

func NewTLSConfig

func NewTLSConfig(certPath, keyPath, caPath string) (*tls.Config, error)

NewTLSConfig returns a TLS config that includes a certificate Use for Server TLS config or when using a client certificate If caPath is empty, system CAs will be used

Types

type GRPCFlags

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

func NewGRPCFlags

func NewGRPCFlags() *GRPCFlags

func (*GRPCFlags) Addr

func (f *GRPCFlags) Addr() string

type HealthProbesFlags

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

func NewHealthProbesFlags

func NewHealthProbesFlags() *HealthProbesFlags

func (*HealthProbesFlags) Addr

func (hpf *HealthProbesFlags) Addr() string

func (*HealthProbesFlags) HealthPath

func (hpf *HealthProbesFlags) HealthPath() string

func (*HealthProbesFlags) ReadyPath

func (hpf *HealthProbesFlags) ReadyPath() string

type InitializerFunc

type InitializerFunc func(context.Context) error

InitializerFunc is a handler that can be passed into WithInitializer to be executed prior to serving

type Option

type Option func(*Server) error

Option is a functional option for creating a Server

func WithGateway

func WithGateway(options ...gateway.Option) Option

WithGateway registers the given gateway options with this server

func WithGrpcServer

func WithGrpcServer(grpcServer *grpc.Server) Option

WithGrpcServer adds the given GRPC server to this server. There can only be one GRPC server within a given instance, so multiple calls with this option will overwrite the previous ones.

func WithHandler

func WithHandler(pattern string, handler http.Handler) Option

WithHandler registers the given http handler to this server by registering the pattern at the root of the http server

func WithHealthChecks

func WithHealthChecks(checker health.Checker) Option

WithHealthChecks registers the given health checker with this server by registering its endpoints at the root of the http server.

func WithInitializer

func WithInitializer(initializerFunc InitializerFunc) Option

WithInitializer adds an initialization function that will get called prior to serving.

func WithInitializerTimeout

func WithInitializerTimeout(timeout time.Duration) Option

WithInitializerTimeout set the duration initialization will wait before halting and returning an error

type Server

type Server struct {

	// GRPCServer will be started whenever this is served
	GRPCServer *grpc.Server

	// HTTPServer will be started whenever this is served
	HTTPServer *http.Server
	// contains filtered or unexported fields
}

Server is a wrapper struct that will allow you to stand up your GPRC server, API Gateway and health checks within the same struct. The recommended way to initialize this is with the NewServer function.

func NewServer

func NewServer(opts ...Option) (*Server, error)

NewServer creates a Server from the given options. All options are processed in the order they are declared.

func (*Server) Serve

func (s *Server) Serve(grpcL, httpL net.Listener) error

Serve invokes all initializers then serves on the given listeners.

If a listener is left blank, then that particular part will not be served.

If a listener is specified for a part that doesn't have a corresponding server, then an error will be returned. This can happen, for instance, whenever a gRPC listener is provided but no gRPC server was set or no option was passed into NewServer.

If both listeners are nil, then an error is returned

func (*Server) Stop

func (s *Server) Stop() error

Stop immediately terminates the grpc and http servers, immediately closing their active listeners

type TLSFlags

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

func NewTLSFlags

func NewTLSFlags() *TLSFlags

func (*TLSFlags) TLSConfig

func (f *TLSFlags) TLSConfig() (*tls.Config, error)

func (*TLSFlags) WithGRPCTLSCreds

func (f *TLSFlags) WithGRPCTLSCreds() (grpc.ServerOption, error)

Jump to

Keyboard shortcuts

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