server

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2024 License: Apache-2.0 Imports: 15 Imported by: 0

README

server

server package helps in setting up grpc server, http server or a mux server that runs both http and grpc on same port on a host It exposes multiple options to configure each of the servers.

Usage

HTTP server
    // context to be Done when SIGINT or SIGTERM is received
	ctx, cancelFunc := context.WithCancel(server.HandleSignals(context.Background()))
	defer cancelFunc()

    // create server.HTTPServer
	s, err := server.NewHTTP(server.Config{
		Port: httpPort,
	})
	if err != nil {
		panic(err)
	}

    // add a handler
	s.RegisterHandler("/ping", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "pong")
	}))

    // start serving
	go s.Serve()
    // wait for ctx context to be set done, by SIGINT or SIGTERM
	<-ctx.Done()

    // set a timer for graceful shutdown, if expired will force kill the server
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*10)
	defer shutdownCancel()

	s.Shutdown(shutdownCtx)
GRPC server
    // grpc middlewares
    var GRPCMiddlewaresInterceptor = grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
	    grpc_recovery.UnaryServerInterceptor(),
	    grpc_ctxtags.UnaryServerInterceptor(),
	    grpc_prometheus.UnaryServerInterceptor,
	    grpc_zap.UnaryServerInterceptor(zap.NewExample()),
    ))

    // context to be Done when SIGINT or SIGTERM is received
	ctx, cancelFunc := context.WithCancel(server.HandleSignals(context.Background()))
	defer cancelFunc()

    // create server.GRPCServer with middlewares
	s, err := server.NewGRPC(server.Config{
		Port: grpcPort,
	}, server.WithGRPCServerOptions(GRPCMiddlewaresInterceptor))
	if err != nil {
		panic(err)
	}

    // register a grpc service desc and server implementation instance
	s.RegisterService(&commonv1.CommonService_ServiceDesc,
		common.New(Server),
	)

    // start serving
	go s.Serve()
    // wait for ctx context to be set done, by SIGINT or SIGTERM
	<-ctx.Done()

    // set a timer for graceful shutdown, if expired will force kill the server
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*10)
	defer shutdownCancel()

	s.Shutdown(shutdownCtx)
GRPC gateway

GRPCGateway can be used to add GRPC Gateway generated proxy handlers to HTTPServer

    gw, err := server.NewGateway("", grpcClientPort)
	if err != nil {
		panic(err)
	}
    // Use the grpc gateway generated function to register http handlers
	gw.RegisterHandler(ctx, commonv1.RegisterCommonServiceHandlerFromEndpoint)

    // set gateway on HTTPServer with /api prefix
	s.SetGateway("/api", gw)
Mux Server

MuxServer can be used to run GRPC and HTTP servers on same port on a host. Internally it uses cmux to route requests to specific server

    // grpc middlewares
    var GRPCMiddlewaresInterceptor = grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
	    grpc_recovery.UnaryServerInterceptor(),
	    grpc_ctxtags.UnaryServerInterceptor(),
	    grpc_prometheus.UnaryServerInterceptor,
	    grpc_zap.UnaryServerInterceptor(zap.NewExample()),
    ))

    // context to be Done when SIGINT or SIGTERM is received
	ctx, cancelFunc := context.WithCancel(server.HandleSignals(context.Background()))
	defer cancelFunc()

    // create server.MuxServer with grpc middlewares
	s, err := server.NewMux(server.Config{
		Port: muxPort,
	}, server.WithMuxGRPCServerOptions(GRPCMiddlewaresInterceptor))
	if err != nil {
		panic(err)
	}

    // use same port for grpc-gateway grpc client to proxy requests to
	grpcClientPort := muxPort
    // create, set handlers and set gateway on MuxServer
	gw, err := server.NewGateway("", grpcClientPort)
	if err != nil {
		panic(err)
	}
	gw.RegisterHandler(ctx, commonv1.RegisterCommonServiceHandlerFromEndpoint)
	s.SetGateway("/api", gw)

    // add additional http handlers on MuxServer
	s.RegisterHandler("/ping", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "pong")
	}))

    // register grpc service on MuxServer
	s.RegisterService(&commonv1.CommonService_ServiceDesc,
		common.New(Server),
	)

    // start serving
	go s.Serve()
    // wait for ctx context to be set done, by SIGINT or SIGTERM
	<-ctx.Done()
	// clean anything that needs to be closed etc like common server implementation etc
    // set a timer for graceful shutdown, if expired will force kill the server
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*10)
	defer shutdownCancel()

	s.Shutdown(shutdownCtx)
Example

For usage example have a look at this - example.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandleSignals

func HandleSignals(ctx context.Context) context.Context

HandleSignals wraps context so that it is marked done when one of SIGINT or SIGTERM is received

Types

type Config

type Config struct {
	Port int
	Host string
}

Config to set the host and port for different servers

type GRPCGateway

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

GRPCGateway helps in registering grpc-gateway proxy handlers for a grpc service on server.HTTPServer

func NewGateway

func NewGateway(host string, port int, opts ...GatewayOption) (*GRPCGateway, error)

NewGateway creates a new server.GRPCGateway to proxy grpc requests to specified host and port.

func (*GRPCGateway) RegisterHandler

func (s *GRPCGateway) RegisterHandler(ctx context.Context, f func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error)) error

RegisterHandler helps in adding routes and handlers to be used for proxying requests to grpc service given the grpc-gateway generated Register*ServiceHandlerFromEndpoint function

type GRPCOption

type GRPCOption func(*grpcOptions)

GRPCOption sets configs, properties or other parameters for the server.GRPCServer

func WithGRPCServer

func WithGRPCServer(grpcServer *grpc.Server) GRPCOption

WithGRPCServer sets grpc.Server instance for server.GRPCServer

func WithGRPCServerOptions

func WithGRPCServerOptions(opts ...grpc.ServerOption) GRPCOption

WithGRPCServerOptions sets []grpc.ServerOption for server.GRPCServer

type GRPCServer deprecated

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

GRPCServer is an server to serve grpc requests

Deprecated: Prefer `mux` package instead of this.

func NewGRPC deprecated

func NewGRPC(config Config, options ...GRPCOption) (*GRPCServer, error)

NewGRPC creates a new server.GRPCServer instance with given config and server.GRPCOption

Deprecated: Prefer `mux` package instead of this.

func (*GRPCServer) RegisterHealth

func (s *GRPCServer) RegisterHealth() *health.Server

RegisterHealth adds standard grpc health check service to grpc server

func (*GRPCServer) RegisterService

func (s *GRPCServer) RegisterService(sd *grpc.ServiceDesc, ss interface{})

func (*GRPCServer) Serve

func (s *GRPCServer) Serve() error

Serve starts the configured grpc server to serve requests

func (*GRPCServer) Shutdown

func (s *GRPCServer) Shutdown(ctx context.Context)

Shutdown gracefully stops the server, and kills the server when passed context is cancelled

type GatewayOption

type GatewayOption func(*gatewayOptions)

GatewayOption sets configs, properties or other parameters for the server.GRPCGateway

func WithGRPCGateway

func WithGRPCGateway(gwmux *runtime.ServeMux) GatewayOption

WithGRPCGateway sets runtime.ServeMux instance for server.GRPCGateway

func WithGatewayMuxOptions

func WithGatewayMuxOptions(opts ...runtime.ServeMuxOption) GatewayOption

WithGatewayMuxOptions sets []runtime.ServeMuxOption for server.GRPCGateway

type HTTPOption

type HTTPOption func(*httpOptions)

HTTPOption sets configs, properties or other parameters for the server.HTTPServer

func WithHTTPServer

func WithHTTPServer(httpServer *http.Server) HTTPOption

WithHTTPServer sets http.Server instance for server.HTTPServer

type HTTPServer deprecated

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

HTTPServer is an server to serve http requests

Deprecated: Prefer `mux` package instead of this.

func NewHTTP deprecated

func NewHTTP(config Config, options ...HTTPOption) (*HTTPServer, error)

NewHTTP creates a new server.HTTPServer instance with given config and server.HTTPOption

Deprecated: Prefer `mux` package instead of this.

func (*HTTPServer) RegisterHandler

func (s *HTTPServer) RegisterHandler(pattern string, handler http.Handler)

RegisterHandler registers provided pattern and handler on the http server

func (*HTTPServer) Serve

func (s *HTTPServer) Serve() error

Serve starts the configured http server to serve requests

func (*HTTPServer) SetGateway

func (s *HTTPServer) SetGateway(patternPrefix string, gw *GRPCGateway)

SetGateway sets a server.GRPCGateway instance on the http server to be proxy requests to a grpc service

func (*HTTPServer) Shutdown

func (s *HTTPServer) Shutdown(ctx context.Context)

Shutdown gracefully stops the server, and kills the server when passed context is cancelled

type MuxOption

type MuxOption func(*muxOptions)

MuxOption sets configs, properties or other parameters for the server.MuxServer

func WithMuxGRPCServer

func WithMuxGRPCServer(grpcServer *grpc.Server) MuxOption

WithMuxGRPCServer sets grpc.Server instance for the internal grpc server of server.MuxServer

func WithMuxGRPCServerOptions

func WithMuxGRPCServerOptions(opts ...grpc.ServerOption) MuxOption

WithMuxGRPCServerOptions sets []grpc.ServerOption for the internal grpc server of server.MuxServer

func WithMuxHTTPServer

func WithMuxHTTPServer(httpServer *http.Server) MuxOption

WithMuxHTTPServer sets http.Server instance for the internal http server of server.MuxServer

type MuxServer deprecated

type MuxServer struct {
	GRPCServer
	HTTPServer
	// contains filtered or unexported fields
}

MuxServer is an server to serve grpc requests and http requests on same host and port

Deprecated: Prefer `mux` package instead of this.

func NewMux deprecated

func NewMux(config Config, options ...MuxOption) (*MuxServer, error)

NewMux creates a new server.MuxServer instance with given config and server.MuxOption

Deprecated: Prefer `mux` package instead of this.

func (*MuxServer) Serve

func (s *MuxServer) Serve() error

Serve starts the configured grpc and http servers to serve requests

func (*MuxServer) Shutdown

func (s *MuxServer) Shutdown(ctx context.Context)

Shutdown gracefully stops the server, and kills the server when passed context is cancelled

Directories

Path Synopsis
proto/gotocompany/common/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.

Jump to

Keyboard shortcuts

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