sweb

package module
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2021 License: MIT Imports: 13 Imported by: 2

README

sweb

Serve webstuff.

What?

This is a quickstart package to get a web server app running, waiting on a port and IP address specified in the environment, and serving static files from a similarly specified directory.

This is geared at things running in typical Docker, AWS etc. setups behind a reverse proxy which handles the domain and certificates. If you need S3, GCP or other special backend storage support, write a route for it. See chi documentation for more on how routing works.

How do I try it?

The minimal example:

srv := sweb.New()
srv.Start()
// do stuff, wait for CTRL-C, whatever
srv.Stop()

This will launch a web server bound to the IP address 127.0.0.1, port 15000, loading static files from the folder static in the working path of the program.

To configure these settings, use the following environment variables:

WEBHOST
WEBPORT
WEBSTATIC

How do I customise the root path?

Embed the Server struct into a struct of your own, run srv.Init(), optionally srv.InitMiddleware() and add routes manually from there with WebGet(), WebGets() and Route().

Example:

type MyServer struct {
	sweb.Server
}
…
srv:=&MyServer{}
// Add router and logger
srv.Init()
// Add four pieces of middleware suitable for HTTP
srv.InitMiddleware()
srv.WebGet("/", srv.Static)
srv.WebGets("/{page}", func(r chi.Router) {
	r.Get("/*", srv.Static)
	r.Options("/", sweb.Preflight)
})
…
srv.Stop()

This works like the simpler example, setting things up like the defaults.

Example setup for a /api route alongside the default handler:

srv.Route("/api", func(r chi.Router) {
	// API middleware
	r.Use(
		middleware.NoCache, // chi
		middleware.RealIP, // chi
		sweb.AddCORS,
		middleware.Timeout(time.Second*10), // chi
	)
	// TODO: Insert r.NotFound(w) call here if desirable
	r.Options("/", sweb.Preflight)
	// Longer endpoints first, otherwise the "/" route will be used for everything
	r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello " + r.RemoteAddr))
	})
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("v1"))
	})
})

Middleware

These middlware functions are available for use, in addition to everything found in chi:

  • AddJSONHeaders: For typical REST endpoints
  • AddHTMLHeaders: For regular browser-friendly pages
  • Preflight: Sets up options for REST calls
  • AddCORS: Allows REST calls from other domains
  • AddSecureHeaders: Forces secure pages when behind a HTTPS reverse proxy

Documentation

Index

Constants

View Source
const (
	// WEBHOST default
	WEBHOST = "127.0.0.1"
	// WEBPORT default
	WEBPORT = "80"
	// WEBSTATIC default
	WEBSTATIC = "static"
)

Variables

This section is empty.

Functions

func AddCORS

func AddCORS(next http.Handler) http.Handler

AddCORS to allow REST access from other domains.

func AddHTMLHeaders

func AddHTMLHeaders(next http.Handler) http.Handler

AddHTMLHeaders for web pages.

func AddJSONHeaders

func AddJSONHeaders(next http.Handler) http.Handler

AddJSONHeaders for JSON responses.

func AddSecureHeaders

func AddSecureHeaders(next http.Handler) http.Handler

AddSecureHeaders for SSL/TLS requests.

func Getenv

func Getenv(k, v string) string

Getenv returns a value for key k, or value v if the environment variable is undefined.

func Parse1123 added in v0.7.0

func Parse1123(s string) time.Time

Parse1123 reads HTTP-sstyle dates properly.

func Preflight

func Preflight(w http.ResponseWriter, r *http.Request)

Preflight returns options for REST calls.

func RealRFC1122Time added in v0.7.0

func RealRFC1122Time(t time.Time) string

RealRFC1122Time makes a HTTP header-compatible date string from the supplied time.

Types

type Server

type Server struct {
	sync.RWMutex
	sync.WaitGroup
	http.Server
	// contains filtered or unexported fields
}

Server structure.

func New

func New() *Server

New server init. Reads settings from environment: WEBHOST - default 127.0.0.1 WEBPORT - default 15000 WEBSTATIC - default "./static/"

func (*Server) AddStartHook added in v0.8.0

func (srv *Server) AddStartHook(h StartHook)

AddStartHook takes a hook function to run before the server starts. You may also return an error, which makes the server fail launch. Hooks are executed in the order they were added.

func (*Server) AddStopHook added in v0.8.0

func (srv *Server) AddStopHook(h StopHook)

AddStopHook takes a hook function to run before the server stops. Hooks are executed in the order they were added.

func (*Server) Init

func (srv *Server) Init()

Init sets up the basics, but no routes.

func (*Server) InitMiddleware

func (srv *Server) InitMiddleware()

InitMiddleware sets up basic middleware on the root web route. These are RealIP and RequestID from chi, a logger for visits and HTML headers.

func (*Server) InitRouter

func (srv *Server) InitRouter()

InitRouter creates the default root router which loads files from the WEBSTATIC path.

func (*Server) Route

func (srv *Server) Route(pattern string, fn func(r chi.Router)) chi.Router

Route adds more sub-routes to a chi route.

func (*Server) ServeFile

func (srv *Server) ServeFile(w http.ResponseWriter, r *http.Request, name string)

ServeFile serves a file from the WEBSTATIC path. NOTE: The server needs to be reloaded if the environment somehow changes.

func (*Server) Start

func (srv *Server) Start() error

Start serving, reconfiguring from any changed environment variables.

func (*Server) Static

func (srv *Server) Static(w http.ResponseWriter, r *http.Request)

Static page serving.

func (*Server) Stop

func (srv *Server) Stop()

Stop serving.

func (*Server) Use added in v0.11.0

func (srv *Server) Use(middlewares ...func(http.Handler) http.Handler)

Use passes middleware to the root web route.

func (*Server) WebGet

func (srv *Server) WebGet(pattern string, handler http.HandlerFunc)

WebGet adds a GET route matching the specified pattern.

func (*Server) WebGets

func (srv *Server) WebGets(pattern string, fn func(r chi.Router))

WebGets adds one or more GET routes to the specified pattern.

func (*Server) WebPost added in v0.10.0

func (srv *Server) WebPost(pattern string, handler http.HandlerFunc)

WebPost adds a POST route matching the specified pattern.

type StartHook added in v0.9.0

type StartHook func() error

StartHook allows for custom setup and cancelling the setup process.

type StopHook added in v0.9.0

type StopHook func()

StopHook allows for custom teardown.

Jump to

Keyboard shortcuts

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