Skip to content

Exposes a reusable HTTP server with graceful shutdown and preconfigured ping, healthcheck and shutdown endpoints.

License

Notifications You must be signed in to change notification settings

cloud-spin/server

Repository files navigation

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.

About

Exposes a reusable HTTP server with graceful shutdown and preconfigured ping, healthcheck and shutdown endpoints.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published