server

package module
Version: v1.5.9 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2018 License: MIT Imports: 13 Imported by: 33

README

server

A wrapper for the net/http server offering a few other features:

  • Config loading from a json config file (for use in setup/handlers)
  • Levelled, Structured logging using a flexible set of loggers - easy to add your own custom loggers
  • Optional logging middleware for requests
  • Scheduling of tasks at specific times of day and intervals
  • Uses the new request context in the Go stdlib
  • Add tracing to requests so that you can follow a request id through handlers
  • Requires Go 1.8

Example usage:


  // Redirect all :80 traffic to our canonical url on :443
	server.StartRedirectAll(80, config.Get("root_url"))

	// If in production, serve over tls with autocerts from let's encrypt
	err = server.StartTLSAutocert(config.Get("autocert_email"), config.Get("autocert_domains"))
	if err != nil {
			server.Fatalf("Error starting server %s", err)
	}

Config

The config package offers access to json config files containing dev/production/test configs.

Example usage:


  // Load config
  config.Load(path)

  // Get a key from our current config (dev/prod/test)
  config.Get("mykey")

Logging

The logging package offers structured, levelled logging which can be configured to send to a file, stdout, and/or other services like an influxdb server with additional plugin loggers. You can add as many loggers which log events as you want, and because logging is structured, each logger can decide which information to act on. Example log output to sdtout is below (real colouring is nicer):

Example usage:

  
  // Set up a stderr logger with time prefix
	logger, err := log.NewStdErr(log.PrefixDateTime)
	if err != nil {
		return err
	}
  
  // Add to the list of loggers receiving events
	log.Add(logger)

2017-01-16:00:37:05 Starting server port:3000 #info 
2017-01-16:00:37:05 Finished loading assets in 109.483µs #info 
2017-01-16:00:37:05 Finished loading templates in 3.184977ms #info 
2017-01-16:00:37:05 Finished opening database in 6.387409ms db:mydb user:myuser #info 
2017-01-16:00:37:05 Finished loading server in 9.99619ms #info 
2017-01-16:00:37:06 <- Request ip:[::1]:64913 len:0 method:GET trace:07466847-28899DB4 url:/ #info 
2017-01-16:00:37:06  in handler using request context trace:07466847-28899DB4 #info 
2017-01-16:00:37:06 -> Response in 3.005292ms trace:07466847-28899DB4 url:/ #info 
2017-01-16:00:37:07 <- Request ip:[::1]:64913 len:0 method:GET trace:A0E55A1B-012DA648 url:/ #info 
2017-01-16:00:37:07  in handler using request context trace:A0E55A1B-012DA648 #info 
2017-01-16:00:37:07 -> Response in 3.32221ms trace:A0E55A1B-012DA648 url:/ #info 

Scheduling

A scheduling facility so that you can schedule actions (like sending a tweet) on app startup.

  
   schedule.At(func(){}, context, time, repeatDuration)

Documentation

Overview

Package server is a wrapper around the stdlib http server and x/autocert pkg.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddCacheHeaders added in v1.5.9

func AddCacheHeaders(w http.ResponseWriter, days int, hash string)

AddCacheHeaders adds Cache-Control, Expires and Etag headers using the age in days and content hash provided

func Redirect added in v1.5.2

func Redirect(w http.ResponseWriter, r *http.Request, path string) error

Redirect uses status 302 StatusFound by default - this is not a permanent redirect We don't accept external or relative paths for security reasons

func RedirectExternal added in v1.5.2

func RedirectExternal(w http.ResponseWriter, r *http.Request, path string) error

RedirectExternal redirects setting the status code (for example unauthorized), but does no checks on the path Use with caution and only on paths *fixed at compile time*.

func RedirectStatus added in v1.5.2

func RedirectStatus(w http.ResponseWriter, r *http.Request, path string, status int) error

RedirectStatus redirects setting the status code (for example unauthorized) We don't accept external or relative paths for security reasons

Types

type Logger

type Logger interface {
	Printf(format string, args ...interface{})
}

Logger interface for a logger - deprecated for 2.0

type Server

type Server struct {

	// Deprecated Logging - due to be removed in 2.0
	// Instead use the structured logging with server/log
	Logger Logger
	// contains filtered or unexported fields
}

Server wraps the stdlib http server and x/autocert pkg with some setup.

func New

func New() (*Server, error)

New creates a new server instance

func (*Server) Config

func (s *Server) Config(key string) string

Config returns a specific configuration value or "" if no value

func (*Server) ConfigBool

func (s *Server) ConfigBool(key string) bool

ConfigBool returns the current configuration value as bool (yes=true, no=false), or false if no value

func (*Server) ConfigInt

func (s *Server) ConfigInt(key string) int64

ConfigInt returns the current configuration value as int64, or 0 if no value

func (*Server) Configuration

func (s *Server) Configuration() map[string]string

Configuration returns the map of configuration keys to values

func (*Server) ConfiguredTLSServer added in v1.5.1

func (s *Server) ConfiguredTLSServer(certManager *autocert.Manager) *http.Server

ConfiguredTLSServer returns a TLS server instance with a secure config this server has read/write timeouts set to 20 seconds, prefers server cipher suites and only uses certain accelerated curves see - https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/

func (*Server) Fatal

func (s *Server) Fatal(format string)

Fatal logs the message, and then exits with status 1

func (*Server) Fatalf

func (s *Server) Fatalf(format string, v ...interface{})

Fatalf the message with the given arguments to our internal logger, and then exits with status 1

func (*Server) Log

func (s *Server) Log(message string)

Log logs the message to our internal logger

func (*Server) Logf

func (s *Server) Logf(format string, v ...interface{})

Logf logs the message with the given arguments to our internal logger

func (*Server) Mode

func (s *Server) Mode() string

Mode returns the mode (production or development)

func (*Server) Port

func (s *Server) Port() int

Port returns the port of the server

func (*Server) PortString added in v1.5.1

func (s *Server) PortString() string

PortString returns a string port suitable for passing to http.Server

func (*Server) Production

func (s *Server) Production() bool

Production tells the caller if this server is in production mode or not?

func (*Server) SetProduction added in v1.5.6

func (s *Server) SetProduction(value bool)

SetProduction sets the mode manually to SetProduction

func (*Server) Start

func (s *Server) Start() error

Start starts an http server on the given port

func (*Server) StartRedirectAll added in v1.5.1

func (s *Server) StartRedirectAll(p int, host string)

StartRedirectAll starts redirecting all requests on the given port to the given host this should be called before StartTLS if redirecting http on port 80 to https

func (*Server) StartTLS added in v1.5.1

func (s *Server) StartTLS(cert, key string) error

StartTLS starts an https server on the given port with tls cert/key from config keys. Settings based on an article by Filippo Valsorda. https://blog.cloudflare.com/exposing-go-on-the-internet/

func (*Server) StartTLSAutocert added in v1.5.1

func (s *Server) StartTLSAutocert(email string, domains string) error

StartTLSAutocert starts an https server on the given port by requesting certs from an ACME provider. The server must be on a public IP which matches the DNS for the domains.

func (*Server) Timef

func (s *Server) Timef(format string, start time.Time, v ...interface{})

Timef logs a time since starting, when used with defer at the start of a function to time Usage: defer s.Timef("Completed %s in %s",time.Now(),args...)

type StatusError added in v1.5.2

type StatusError struct {
	Err     error
	Status  int
	Title   string
	Message string
	File    string
	Line    int
}

StatusError wraps a std error and stores more information (status code, display title/msg and caller info)

func BadRequestError added in v1.5.2

func BadRequestError(e error, args ...string) *StatusError

BadRequestError returns a new StatusError with Status StatusBadRequest and optional Title and Message

func Error added in v1.5.2

func Error(e error, s int, t string, m string) *StatusError

Error returns a new StatusError with code StatusInternalServerError and a generic message

func InternalError added in v1.5.2

func InternalError(e error, args ...string) *StatusError

InternalError returns a new StatusError with Status StatusInternalServerError and optional Title and Message Usage: return router.InternalError(err)

func NotAuthorizedError added in v1.5.2

func NotAuthorizedError(e error, args ...string) *StatusError

NotAuthorizedError returns a new StatusError with Status StatusUnauthorized and optional Title and Message

func NotFoundError added in v1.5.2

func NotFoundError(e error, args ...string) *StatusError

NotFoundError returns a new StatusError with Status StatusNotFound and optional Title and Message Usage return router.NotFoundError(err,"Optional Title", "Optional user-friendly Message")

func ToStatusError added in v1.5.2

func ToStatusError(e error) *StatusError

ToStatusError returns a *StatusError or wraps a standard error in a 500 StatusError

func (*StatusError) Error added in v1.5.2

func (e *StatusError) Error() string

Error returns the underling error string - it should not be shown in production

func (*StatusError) FileLine added in v1.5.2

func (e *StatusError) FileLine() string

FileLine returns file name and line of error

func (*StatusError) String added in v1.5.2

func (e *StatusError) String() string

String returns a string represenation of this error, useful for debugging

Directories

Path Synopsis
Package config offers utilities for parsing a json config file.
Package config offers utilities for parsing a json config file.
Package log provides a structured, levelled logger interface for use in server handlers, which handles multiple output streams.
Package log provides a structured, levelled logger interface for use in server handlers, which handles multiple output streams.
Package schedule provides a simple way to schedule functions at a time or interval Package schedule provides a simple way to schedule functions at a time or interval
Package schedule provides a simple way to schedule functions at a time or interval Package schedule provides a simple way to schedule functions at a time or interval

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL