opirou

package module
v0.0.0-...-862f642 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2022 License: MIT Imports: 11 Imported by: 0

README

opirou

opinionated router

Go Reference

Features

  • regex routes
  • named url parameters
  • custom html include tags

Usage

package main

import (
	"fmt"
	"io"
	"net/http"

	"github.com/dougty/opirou"
)

// optional log.Logger argument for errors
var router *opirou.Router = opirou.NewRouter(nil)

func main() {
	// create a route
	router.Route("GET", "/test/@foo/@bar", testRoute)

	// ...or use a helper function (POST, PUT, etc...)
	router.GET(`/path/.+`, regexRoute)

	http.ListenAndServe(":8888", router)
}

// http://localhost:8888/test/abc/123
func testRoute(w http.ResponseWriter, r *http.Request, p opirou.Params) {
	io.WriteString(w, "hello browser\n")
	fmt.Println(p["foo"], p["bar"]) // access url params by name
}

Static files

Static files can be served in a couple different ways...

// ...as a single file
router.GET("/", router.StaticFile("./static/index.html"))

// ...as a directory
// router.Dir creates a pattern usable with router.StaticDir
router.GET(router.Dir("/assets"), router.StaticDir("./static"))

Late routes

Late routes will match after all other routes so that you can use them as a 'wildcard'
without having to worry about the order in which routes are defined. This allows for a
cleaner alternative to serving a static directory as your 404 not found route.

// create a late route
router.LateRoute("GET", router.Dir("/assets"), router.StaticDir("./static"))

Custom 404 route

By default http.NotFound will be called when no route matches a URL.
There are a few different ways to define your own...

// ...as a route callback
router.SetNotFound(func(w http.ResponseWriter, r *http.Request, p opirou.Params) {
	io.WriteString(w, "couldn't find that!\n")
})

// ...as a static file
router.SetNotFound(router.StaticFile("./static/404.html"))

// ...as a static directory
// using a late route instead is recommended
router.SetNotFound(router.StaticDir("./static"))

Authentication

Conditionally serving routes can be accomplished by wrapping your callback function...

func AuthWrapper(cb opirou.Callback) opirou.Callback {
	return func(w http.ResponseWriter, r *http.Request, p opirou.Params) {
		someCondition := false
		if someCondition {
			cb(w, r, p)
		} else {
			status := http.StatusUnauthorized
			http.Error(w, http.StatusText(status), status)
		}
	}
}

router.GET(router.Dir("/admin"), AuthWrapper(router.StaticDir("./static")))

HTML Preprocessing

HTML files can be optionally preprocessed to parse include tags and environment variable conditionals

// all statically served *.html files will be preprocessed
router.EnableHTML(true)
// replaced with the contents of foobar.html
// can be nested as much as needed
<!-- include "foobar.html" -->

// replaced with the text inside { } if DEV=1 is in env
<!-- if $DEV { <script src="dev.js"></script> } -->

// can be negated with ! for when env var is not present or 0
<!-- if !$DEV { <script src="prod.js"></script> } -->

Disable caching

Route and HTML caching can be disabled for development purposes with the env var NOCACHE=1

Deleting routes

// remove route completely
router.RemoveRoute("/path/@param")

// clear cache if routes are updated at runtime
router.ClearCache("/path/@param")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Callback

type Callback func(http.ResponseWriter, *http.Request, Params)

type Params

type Params map[string]string

contains url parameters (if any)

type Router

type Router struct {
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(logger *log.Logger) *Router

create and initialize new router

specify logger to use, or 'nil' to create a new one internally

func (*Router) ClearCache

func (router *Router) ClearCache(str string)

clear cached routes that match a pattern

func (*Router) DELETE

func (router *Router) DELETE(str string, cb Callback)

func (*Router) Dir

func (router *Router) Dir(str string) string

returns a pattern to match a dir (for use with StaticDir)

func (*Router) EnableHTML

func (router *Router) EnableHTML(b bool)

enables html preprocessing for custom include tags

func (*Router) GET

func (router *Router) GET(str string, cb Callback)

func (*Router) HEAD

func (router *Router) HEAD(str string, cb Callback)

func (*Router) LateRoute

func (router *Router) LateRoute(method string, str string, cb Callback)

func (*Router) PATCH

func (router *Router) PATCH(str string, cb Callback)

func (*Router) POST

func (router *Router) POST(str string, cb Callback)

func (*Router) PUT

func (router *Router) PUT(str string, cb Callback)

func (*Router) RemoveRoute

func (router *Router) RemoveRoute(str string)

remove routes that match a pattern

func (*Router) Route

func (router *Router) Route(method string, str string, cb Callback)

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Router) SetNotFound

func (router *Router) SetNotFound(cb Callback)

set 404 not found route

func (*Router) StaticDir

func (router *Router) StaticDir(dir string) func(http.ResponseWriter, *http.Request, Params)

returns a Callback function for serving static files from a directory

func (*Router) StaticFile

func (router *Router) StaticFile(fn string) func(http.ResponseWriter, *http.Request, Params)

returns a Callback function for serving a single static file

Jump to

Keyboard shortcuts

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