server

package module
v0.0.0-...-8785abe Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2018 License: MIT Imports: 8 Imported by: 0

README

Server Build Status codecov Go Report Card GoDoc

Server exposes a reusable HTTP server with graceful shutdown and preconfigured ping, health check and shutdown endpoints. Server uses gorilla/mux as its main request router.

Install

From a configured Go environment:

go get -u github.com/cloud-spin/server

If you are using dep:

dep ensure -add github.com/cloud-spin/server
How to Use

Below example starts a fully working HTTP server, test it by pinging its pre-configured "/ping" endpoint and shuts it down gracefully afterwards.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/cloud-spin/server"
	"github.com/gorilla/mux"
)

func main() {
	configs := server.NewConfigs()
	s := server.New(configs, mux.NewRouter())

	go func() {
		if err := s.Start(); err != nil {
			log.Println("Error serving requests")
			log.Fatal(err)
		}
	}()

	// Test if the server was initialized successfully by pinging its "/ping" endpoint.
	resp, err := http.Get(fmt.Sprintf("http://localhost:%d/%s", configs.Port, configs.PingEndpoint))
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(resp.StatusCode)
	}

	s.Stop()
}

Output:

200

Also refer to the tests at server_test.go.

Handlers

Package server uses http.ListenAndSeve by default to start the HTTP server. However, this can be overriden to be used any other http methods to start the server such as http.ListenAndServeTLS or any other custom function. Below code register a custom handler and start the server with http.ListenAndServeTLS instead of the default http.ListenAndServe.

...
s := server.New(configs, router)
s.RegisterServerStartHandler(func(s *http.Server) error {
	return s.ListenAndServeTLS(...)
})

go func() {
	if err := s.Start(); err != nil {
		log.Println("Error serving requests")
		log.Fatal(err)
	}
}()

Package server also provides a shutdown hook that can be used to release the system resources at shutdown time. Below code register a custom shutdown handler that gets executed when the http server is shutting down.

...
s := server.New(configs, router)
s.RegisterOnShutdown(func() {
	fmt.Println("shutting down server")
})
		
go func() {
	if err := s.Start(); err != nil {
		log.Println("Error serving requests")
		log.Fatal(err)
	}
}()

License

MIT, see LICENSE.

"Use, abuse, have fun and contribute back!"

Contributions

See contributing.md.

Documentation

Overview

Package server exposes a reusable HTTP server with graceful shutdown and preconfigured ping, health check and shutdown endpoints. Server uses gorilla/mux(https://github.com/gorilla/mux) as its main request router.

Index

Constants

View Source
const (
	// DefaultPort holds the default port the server will listen on.
	DefaultPort = 9090

	// DefaultShutdownTimeout holds the timeout to shutdown the server.
	DefaultShutdownTimeout = 10 * time.Second

	// DefaultReadTimeout holds the default read timeout.
	DefaultReadTimeout = 15 * time.Second

	// DefaultWriteTimeout holds the default write timeout.
	DefaultWriteTimeout = 15 * time.Second

	// DefaultPingEndpoint holds the default ping endpoint.
	DefaultPingEndpoint = "/ping"

	// DefaultHealthcheckEndpoint holds the default healtcheck endpoint.
	DefaultHealthcheckEndpoint = "/healthcheck"

	// DefaultShutdownEndpoint holds the default shutdown endpoint.
	DefaultShutdownEndpoint = "/shutdown"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Configs

type Configs struct {
	Port                int
	ShutdownTimeout     time.Duration
	ReadTimeout         time.Duration
	WriteTimeout        time.Duration
	PingEndpoint        string
	HealthcheckEndpoint string
	ShutdownEndpoint    string
}

Configs holds server specific configs. Port holds the server port. ShutdownTimeout holds the timeout to shutdown the server. ReadTimeout holds the read timeout. WriteTimeout holds the write timeout. PingEndpoint holds the ping endpoint. HealthcheckEndpoint holds the healthcheck endpoint. ShutdownEndpoint holds the shutdown endpoint.

func NewConfigs

func NewConfigs() *Configs

NewConfigs initializes a new instance of Configs with default values.

type Server

type Server interface {
	Start() error
	Stop() error
	GetHTTPServer() *http.Server
	RegisterOnShutdown(f func())
	RegisterServerStartHandler(f func(s *http.Server) error)
	RegisterHealthcheckEndpoint(path string, handler func(w http.ResponseWriter, r *http.Request))
	RegisterServerShutdownHandler(f ShutdownHandler)
}

Server represents a HTTP server.

func New

func New(configs *Configs, router *mux.Router) Server

New initializes a new instance of Server.

type ServerImpl

type ServerImpl struct {
	Configs    *Configs
	Router     *mux.Router
	HTTPServer *http.Server
	// contains filtered or unexported fields
}

ServerImpl implements a HTTP Server.

func (*ServerImpl) GetHTTPServer

func (s *ServerImpl) GetHTTPServer() *http.Server

GetHTTPServer returns the HTTP server instance,

func (*ServerImpl) RegisterHealthcheckEndpoint

func (s *ServerImpl) RegisterHealthcheckEndpoint(path string, handler func(w http.ResponseWriter, r *http.Request))

RegisterHealthcheckEndpoint register the handler to handle healthcheck responses.

func (*ServerImpl) RegisterOnShutdown

func (s *ServerImpl) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to call on Shutdown. It delegates the calls to the standard http.Server package.

func (*ServerImpl) RegisterServerShutdownHandler

func (s *ServerImpl) RegisterServerShutdownHandler(f ShutdownHandler)

RegisterServerShutdownHandler registers a function that should shutdown the HTTP server.

func (*ServerImpl) RegisterServerStartHandler

func (s *ServerImpl) RegisterServerStartHandler(f func(s *http.Server) error)

RegisterServerStartHandler registers a function that should start the HTTP server.

func (*ServerImpl) Start

func (s *ServerImpl) Start() error

Start starts the server and blocks, listening for requests.

func (*ServerImpl) Stop

func (s *ServerImpl) Stop() error

Stop stops the server gracefully and synchronously, returning any error detected during shutdown. The ShutdownTimeout is respected for all in-flight requests. When the server is no longer processing any requests, Stop() will return and the server won't listen for requests anymore.

type ShutdownHandler

type ShutdownHandler = func(s *http.Server, ctx context.Context) error

ShutdownHandler is fired when the server should be shutdown.

Jump to

Keyboard shortcuts

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