tube

package module
v0.0.0-...-9d47ca1 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2024 License: MIT Imports: 12 Imported by: 0

README

tube

yet another go router

the internet is a series of tubes
this is just one of them

features

  • regex routes
  • named url parameters
  • html include tags

usage

package main
import (
	"fmt"
	"io"
	"net/http"
	"github.com/dougty/tube"
)
// optional log.Logger argument
var router *tube.Router = tube.NewRouter(nil)
func main() {
	// create a GET route
	router.GET("/test/@foo/@bar", testRoute)
	// listen with standard go net/http server
	http.ListenAndServe(":8888", router)
}
// http://localhost:8888/test/abc/123
func testRoute(d *tube.Data) {
	// send a response
	d.Write("hello browser\n")
	// access url params by name
	fmt.Println(d.Params["foo"], d.Params["bar"])
}

static files

static files can be served in a couple ways...

// ...as a single file
router.GET("/", router.StaticFile("./static/index.html"))
// ...as a directory
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.

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

custom error routes

you can define your own 404 and 500 routes a couple ways...

// ...as a route callback
router.Set404(func(d *tube.Data) {
	d.Write("couldn't find that!\n")
})
// ...as a static file
router.Set404(router.StaticFile("./static/404.html"))

authentication

conditionally serving routes can be achieved by wrapping your callback...

func AuthWrapper(cb tube.Callback) tube.Callback {
	return func(d *tube.Data) {
		someCondition := false
		if someCondition {
			cb(d)
		} else {
			d.Status(http.StatusUnauthorized)
			d.Write("unauthorized")
		}
	}
}
router.GET(router.Dir("/admin"), AuthWrapper(router.StaticDir("./static")))

html preprocessing

html files are preprocessed to parse include tags and more
this behaviour can be disabled with the env NOHTML=1

// you can also return html from a route callback
func myRouteCallback(d *tube.data) {
	d.HTML += `<!-- include "test.html" -->`
}
// replaced with the contents of foobar.html
// can be nested as much as needed (don't loop!)
// paths are relative to the current file
<!-- include "subdir/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 isn't present or == 0
<!-- if !$DEV { <script src="production.js"></script> } -->

disable caching

route and html caching can be disabled for debug with the env NOCACHE=1

deleting routes

// remove route completely
router.RemoveRoute("/users/@name")
// clear cache if routes are updated at runtime
router.ClearCache("/users/doug")

Documentation

Index

Constants

View Source
const (
	LOG_ERRORS int = iota
	LOG_INFO
	LOG_DEBUG
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Callback

type Callback func(*Data)

type Data

type Data struct {
	Writer  http.ResponseWriter // http writer
	Request *http.Request       // http request
	Params  Params              // url params

	HTML string // html response to be parsed
	// contains filtered or unexported fields
}

route callback data

func (*Data) Error

func (d *Data) Error(err error)

sends '500 internal server error'

func (*Data) Json

func (d *Data) Json(v interface{}) error

get json request data

func (*Data) NotFound

func (d *Data) NotFound()

sends and caches '404 not found'

func (*Data) P

func (d *Data) P(name string) string

param helper

func (*Data) Redirect

func (d *Data) Redirect(url string, code int)

send redirect

func (*Data) Status

func (d *Data) Status(code int)

write status code

func (*Data) Write

func (d *Data) Write(str string)

write string response

func (*Data) WriteJson

func (d *Data) WriteJson(v interface{}) error

write json response

type Params

type Params map[string]string

map of url params by @name

type Router

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

func NewRouter

func NewRouter() *Router

create and initialize new router

func (*Router) ClearCache

func (router *Router) ClearCache(str string)

clear cache that matches 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 whole dir (for use with StaticDir)

func (*Router) EmptyCache

func (router *Router) EmptyCache()

empty cache completely

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)

removes routes that patch 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) Set404

func (router *Router) Set404(cb Callback)

set 404 route

func (*Router) Set500

func (router *Router) Set500(cb Callback)

set 500 route

func (*Router) SetLogLevel

func (router *Router) SetLogLevel(i int)

set log level

func (*Router) SetLogger

func (router *Router) SetLogger(logger *log.Logger)

set logger

func (*Router) StaticDir

func (router *Router) StaticDir(dir string) func(*Data)

returns a Callback function for serving static files from a directory

func (*Router) StaticFile

func (router *Router) StaticFile(fn string) func(*Data)

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