fortressgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2019 License: MIT Imports: 23 Imported by: 0

README

FORTRESS GO

Go Report Card Issues Pull Requests License Size Release

Visit the Fortress Go web site.

Easily write secure, fast, production-ready web sites and servers in Golang.

Want to create a secure site in Go? It's a fantastic choice but unlike Ruby (with Rails), C# (with Asp.Net MVC), or Python (with Django or Flask) it isn't obvious where to start if you want to go beyond the (excellent) tutorials on request routing, handlers, and middleware.

Include Fortress Go in your own application and with a simple set of configuration options you get a standard server with masses of extras built in. Deploy with confidence.

  • Standard HTTP(S) server with standard handlers and routing.
  • Automatic LetsEncrypt (HTTPS) by specifying port 443.
  • Restrict the server by hostname.
  • Serve static assets (CSS, JavaScript etc) from a specified folder.
  • HTML templates automatically loaded and cached.
  • Helper method executes any cached template with any data.
  • Built-in template functions including Markdown rendering.
  • Panic handling (server continues).
  • Request logging in Apache format (stdout or custom destination).
  • Secure and encrypted cookies with explicit lifetimes and easy usage.
  • Cookie based session support.
  • User login/logout/get current.
  • Public and signed-in routes.
  • Per request cookie based CSRF.
  • CORS with support for headers, methods, and origins.
  • CSP (content security policy) for default, styles, and scripts.
  • Optional middleware converts from status codes to displaying an error template.
  • Optional database (MySQL/MariaDB currently) ping at startup with connection made available to all handlers.
  • Load server configuration from a config file.
  • Enforce JSON or XML content types for a request (and set response content type).
  • Session-based flash messages with optional remove-on-retrieval.

Note that although MySQL/MariaDB is mentioned above, the server is standard Go so other database options can be used as normal.

How do I use it?

It's ready and fully usable, though not yet documented. In the meantime the example folder (see below) shows how incredibly simple it can be.

Requirements

  • Go v1.7 or later

What does it use in the background?

Standing on the shoulders of giants ...

  • The Go standard library authors
  • Gorilla web toolkit - cookies, sessions, routing, logging, panics
  • Russ Ross - Black Friday for Markdown rendering
  • LetsEncrypt - issuers for auto-renewing certificates
  • Julian Schmidt and others for the MySQL library
  • Jason Moiron for the SQLX extensions

Custom code has been kept to a minimum and mostly consists of setup/orchestration/simplification of the above. The exceptions are CSRF, CORS, CSP, simple user protection, and configuration loading. These were added by myself.

Possibly incoming (in no particular order)

  • Error logging (possibly to a third party).
  • Response caching.

Running the example

The example folder contains an example of how to use the Fortress Go package.

There are pre-built cross-platform versions, but do not run them directly from the example/builds subfolder as they will be unable to find their templates and static content due to the path. Run them like so:

cd example

./builds/macos/example  # Mac OS
./builds/linux/example  # Linux
builds/windows/example  # Windows

There are a few sample handlers, the routes to which can be found in example/main.go - also linked to on a menu when the example runs. Press Ctrl-C to stop the server.

The example has a config.ini file holding its settings, and the main.go file shows it being used. You can ignore that file and set all the options directly by populating your own ServerConfig in code.


Changing Fortress Go itself

If you are writing your own site and are including Fortress Go as it stands then you don't need to read any further. What follows is for people who want to make changes to Fortress Go's own behaviour.

Build and run the example for your current system
dep ensure
cd example

go build -o builds/macos/example && ./builds/macos/example  # Mac OS
go build -o builds/linux/example && ./builds/linux/example  # Linux
go build -o builds\windows\example.exe && .\builds\windows\example.exe  # Windows
Create cross-platform builds of the example

Run the script (below) that corresponds to your system. Each of the three scripts builds for all three platforms.

dep ensure
cd example

./scripts/macos.sh  # Mac OS
./scripts/linux.sh  # Linux
.\scripts\windows.bat  # Windows

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CORSOptions

type CORSOptions struct {
	Origins, Methods, Headers []string
}

CORSOptions ... Defines the options for the CORS headers.

type CSRFOptions

type CSRFOptions struct {
	Minutes    int
	CookieName string
}

CSRFOptions ... Defines the options for the CSRF token.

type ContentSecurityPolicy

type ContentSecurityPolicy struct {
	Default, Script, Style, Font []string
}

ContentSecurityPolicy ... Defines the CSP for header generation.

type Folders

type Folders struct {
	Templates, LetsEncrypt, StaticContent string
}

Folders ... Details various file system locations.

type Server

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

Server ... Holds all the config and running instance of the web server.

func NewServer

func NewServer(config ServerConfig) Server

NewServer ... Creates a new server with hostname router etc.

func (*Server) AddFlashMessage

func (s *Server) AddFlashMessage(w http.ResponseWriter, r *http.Request, value string) error

AddFlashMessage ... Adds a one-time flash message to the session.

func (*Server) ApplyTemplate

func (s *Server) ApplyTemplate(w http.ResponseWriter, name string, data interface{}) error

ApplyTemplate ... Writes the named template with the given data.

func (*Server) CORS

func (s *Server) CORS(h http.Handler) http.Handler

CORS ... Applies any relevant CORS headers.

func (*Server) CSP

func (s *Server) CSP(h http.Handler) http.Handler

CSP ... Applies any relevant CSP headers.

func (*Server) CSRF

func (s *Server) CSRF(h http.Handler) http.Handler

CSRF ... Enforces the CSRF token requirement.

func (*Server) DB

func (s *Server) DB() *sqlx.DB

DB ... The shared database connection (long-lived; don't close).

func (*Server) ErrorCheck

func (s *Server) ErrorCheck(err error, w http.ResponseWriter, statusCode int, text string) bool

ErrorCheck ... If there is an error, send it (with status/text) and return true. If the error template is switched on then it skips the header and passes on the details.

func (*Server) GetCSRF

func (s *Server) GetCSRF(w http.ResponseWriter, r *http.Request) template.HTML

GetCSRF ... Gets a request-specific CSRF token (also placed into a cookie for CSRF middleware checks).

func (*Server) GetCookie

func (s *Server) GetCookie(r *http.Request, name string) (string, error)

GetCookie ... Gets a secure cookie.

func (*Server) GetCurrentUser

func (s *Server) GetCurrentUser(r *http.Request) (User, error)

GetCurrentUser ... Gets the user from a secure cookie (0 for none).

func (*Server) GetDescription

func (s *Server) GetDescription() string

GetDescription ... Gets a simple string description of the server (for UI purposes).

func (*Server) GetFlashMessages

func (s *Server) GetFlashMessages(w http.ResponseWriter, r *http.Request, clear bool) []string

GetFlashMessages ... Gets the one-time flash messages from the session. Deliberately not returning an error for ease of use.

func (*Server) GetSession

func (s *Server) GetSession(r *http.Request, key string, defaultValue interface{}) (interface{}, error)

GetSession ... Gets a (secure cookie) session value.

func (*Server) JSON

func (s *Server) JSON(h http.Handler) http.Handler

JSON ... Ensures JSON request and response content types.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe ... Serves on configured port, with auto-HTTPS for port 443.

func (*Server) LogoutCurrentUser

func (s *Server) LogoutCurrentUser(w http.ResponseWriter, r *http.Request) error

LogoutCurrentUser ... Removes the secure cookie for the user.

func (*Server) RegisterSessionType

func (s *Server) RegisterSessionType(value interface{})

RegisterSessionType ... Registers a type for use in sessions.

func (*Server) RemoveCookie

func (s *Server) RemoveCookie(w http.ResponseWriter, r *http.Request, name string) error

RemoveCookie ... Removes a secure cookie.

func (*Server) ServerErrorCheck

func (s *Server) ServerErrorCheck(err error, w http.ResponseWriter, r *http.Request) bool

ServerErrorCheck ... If there is an error, send it (as a 500) and return true. If the error template is switched on then it skips the header and passes on the details.

func (*Server) SetCookie

func (s *Server) SetCookie(w http.ResponseWriter, name string, value string, minutes int) error

SetCookie ... Sets a secure cookie.

func (*Server) SetCurrentUser

func (s *Server) SetCurrentUser(w http.ResponseWriter, r *http.Request, user User) error

SetCurrentUser ... Sets the user in a secure cookie; use 0 for none.

func (*Server) SetSession

func (s *Server) SetSession(w http.ResponseWriter, r *http.Request, key string, value interface{}) error

SetSession ... Sets a (secure cookie) session value.

func (*Server) SetStatus

func (s *Server) SetStatus(w http.ResponseWriter, statusCode int, text string)

SetStatus ... Issues a standard status code/text and continues. If the error template is switched on then it skips the header and passes on the details.

func (*Server) UsersOnly

func (s *Server) UsersOnly(h http.Handler) http.Handler

UsersOnly ... Ensures the handler is only reachable for signed-in users.

func (*Server) XML

func (s *Server) XML(h http.Handler) http.Handler

XML ... Ensures XML request and response content types.

type ServerConfig

type ServerConfig struct {
	Hostname, StaticPath      string
	Port                      int
	Logger                    io.Writer
	LogToStdout, HandlePanic  bool
	LoginRoute, ErrorTemplate string
	Folders                   Folders
	SessionOptions            SessionOptions
	CSRFOptions               CSRFOptions
	CORSOptions               CORSOptions
	CSPOptions                ContentSecurityPolicy
	DBConnectionString        string
}

ServerConfig ... Defines the server behaviour.

func LoadServerConfig

func LoadServerConfig(filename string) (ServerConfig, error)

LoadServerConfig ... Loads from the specified file (ini format).

type SessionOptions

type SessionOptions struct {
	Minutes               int
	CookieName, CookieKey string
}

SessionOptions ... Defines the options for sessions.

type User

type User struct {
	ID            int
	Display, Role string
}

User ... The user record as persisted in the secure cookie.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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