mux

package module
v0.0.0-...-306f517 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2021 License: Apache-2.0 Imports: 10 Imported by: 0

README

An evolutive multiplexer for HTTP routes

Read HTTP requests, tests matchers then route the good handler.

Add in your project

Load module:

go get github.com/karkael64/golang-mux

Use in your project file

Here is an exemple for adding a route in your HttpServer.

import (
  "fmt"
  mux "github.com/karkael64/golang-mux"
)

func main() {
  var address = "localhost:4242"
  var srv = mux.New()

  srv.AddRoute(getWelcomeRoute())

  fmt.Printf("Starting server at https://%s/\n", address)
  err := srv.Listen(address, "keys/cert.pem", "keys/priv.key")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
}

func getWelcomeRoute() *mux.Route {
	return mux.CreateRoute(
    mux.MatchPathExact([]string{"GET"}, `/welcome`),
    func (w http.ResponseWriter, r *http.Request) error {
      w.Write("Welcome!")
    },
  )
}

Create a route

A route is composed by a matcher and a handler:

  • The matcher is a function which tests the request. It returns a success boolean and an error. If it returns a success, the handler is executed, else it test next route matcher. If any matcher returns an error and none matchs the request, then the error is thrown to client. It is helpfull for forbidden requests (code 403).
  • The handler is a function which write the response HTTP for client. It expect to write a code, headers and a body for client and return nil. The handler can return error about to be thrown to client.
type Handler func(w http.ResponseWriter, r *http.Request) error
type Matcher func(r *http.Request) (bool, error)
type Route struct {
	handler Handler
	match   Matcher
}

You can write a route with the function mux.CreateRoute:

func matcher(r *http.Request) (bool, error) {
  if !len(r.Header()["Token"][0]) {
    return false, mux.NewHttpError(403, "Forbidden")
  }
  return true
}

func handler(w http.ResponseWriter, r *http.Request) error {
  w.Write("Allowed")
}

func init() {
  var route = mux.CreateRoute(matcher, handler)
}

Create a simple file handler

Create a handler for a file with GET method. The example below does match exactly /file path in request and returns the file content at path ./file, with header

func init() {
  var fileRoute = mux.CreateFileRoute(
    "/file",
    "./file",
    http.Header{"Field":{"Value"}}
  )
}

Create a route matching regexp

func init() {
  var regexpMatcher = mux.MatchPathRegexp([]string{"GET"}, `/regexp/\w+`)
}

The matcher can return a boolean and an error. The error could be:

  • The method is not allowed, return HttpError(403)
  • The regexp is not well formatted, return the regexp error

Notes

  • File .env can set HTTP_DEBUG status:
    • if not set, does not display any debug texts
    • if set by HTTP_DEBUG=full, display every errors found
    • if set with empty value HTTP_DEBUG (or any value not full), display only working directory errors

Documentation

Index

Constants

View Source
const STACK_MAX_DEEP = 16
View Source
const STACK_SKIP = 3

Variables

View Source
var METHODS = []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}

Functions

func StackFrameToString

func StackFrameToString(frame *HttpErrorStack) string

func StackToString

func StackToString(stack []HttpErrorStack) string

Types

type ErrorHandler

type ErrorHandler func(e *HttpError, w http.ResponseWriter, r *http.Request)

type Handler

type Handler func(w http.ResponseWriter, r *http.Request) error

Server const and types

func CreateFileHandler

func CreateFileHandler(filePath string, writeHeaders http.Header) Handler

Create handlers

type HttpError

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

func FromError

func FromError(err error) *HttpError

func NewHttpError

func NewHttpError(code int, message string) *HttpError

func (*HttpError) Error

func (err *HttpError) Error() string

func (*HttpError) GetCode

func (err *HttpError) GetCode() int

func (*HttpError) GetMessage

func (err *HttpError) GetMessage() string

func (*HttpError) GetStack

func (err *HttpError) GetStack() []HttpErrorStack

func (*HttpError) GetStackString

func (err *HttpError) GetStackString() string

func (*HttpError) GetTitle

func (err *HttpError) GetTitle() string

func (*HttpError) Send

func (err *HttpError) Send(w http.ResponseWriter)

type HttpErrorStack

type HttpErrorStack struct {
	Function string
	File     string
	AbsFile  string
	Line     int
}

func GetCurrentStack

func GetCurrentStack(skip, maxDeep int) []HttpErrorStack

type Matcher

type Matcher func(r *http.Request) (bool, error)

func MatchPathExact

func MatchPathExact(methods []string, exact string) Matcher

Create matchers

func MatchPathRegexp

func MatchPathRegexp(methods []string, rx string) Matcher

func MatchPathStartWith

func MatchPathStartWith(methods []string, startWith string) Matcher

type Mux

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

Mux type and methods

func New

func New() *Mux

func (*Mux) AddRoute

func (s *Mux) AddRoute(route *Route)

setters

func (*Mux) AddRoutes

func (s *Mux) AddRoutes(routes []*Route)

func (*Mux) Listen

func (s *Mux) Listen(address, pubPath, prvPath string) error

func (*Mux) ServeHTTP

func (s *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Mux) SetDefaultHandler

func (s *Mux) SetDefaultHandler(handler Handler)

func (*Mux) SetErrorHandler

func (s *Mux) SetErrorHandler(handler ErrorHandler)

type Route

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

func CreateFileRoute

func CreateFileRoute(exact string, filePath string, writeHeaders http.Header) *Route

func CreateRoute

func CreateRoute(match Matcher, handler Handler) *Route

Create routes

Jump to

Keyboard shortcuts

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