symple

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2025 License: MIT Imports: 17 Imported by: 0

README

Symple v0.1.0

Motivation

TODO

Install

go get -u github.com/ClMarlier/symple

Features

Usage

import (
        "fmt"
        "log"
        "net/http"
        "os"
        "strconv"

        "github.com/ClMarlier/symple"
)

func main() {
        // ErrFuncDefault is used to handle client response in case of an error
        // occuring anywhere in the chain of middleware or the handler itself.
        // You can provide your own implementation
        rs := symple.NewRouter(symple.ErrFuncDefault)

        mux, err := rs.Router(
                rs.WithZeroLog(os.Stdout),
                rs.WithRecoverer(true),
                rs.WithRoute("GET /hello", hello),
                rs.WithRouter(
                        rs.WithPrefix("/error"),
                        rs.WithRoute("GET /simple", simpleError),
                        rs.WithRoute("GET /panic/{n}", panicError),
                ),
        )
        if err != nil {
                log.Fatal(err)
        }
        log.Fatal(http.ListenAndServe(":8000", mux))
}

func hello(w http.ResponseWriter, r *http.Request) error {
        _, err := w.Write([]byte("Hello World"))
        return err
}

func simpleError(w http.ResponseWriter, _ *http.Request) error {
        return fmt.Errorf("%w custom description of the error", symple.ErrUnauthorized)
}

// to get a panic simply call with n=0
func panicError(w http.ResponseWriter, r *http.Request) error {
        pathNumber := r.PathValue("n")
        n, err := strconv.ParseInt(pathNumber, 10, 32)
        if err != nil {
                http.Error(w, err.Error(), http.StatusUnprocessableEntity)
        }
        res := 666 / n
        _, err = w.Write([]byte(fmt.Sprintf("666/%d = %d", n, res)))
        return err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest                    = Error{"bad request", http.StatusBadRequest}
	ErrUnauthorized                  = Error{"unauthorized", http.StatusUnauthorized}
	ErrPaymentRequired               = Error{"payment required", http.StatusPaymentRequired}
	ErrForbidden                     = Error{"forbidden", http.StatusForbidden}
	ErrNotFound                      = Error{"ressource not found", http.StatusNotFound}
	ErrMethodNotAllowed              = Error{"method not allowed", http.StatusMethodNotAllowed}
	ErrNotAcceptable                 = Error{"not acceptable", http.StatusNotAcceptable}
	ErrProxyAuthRequired             = Error{"proxy authentication required", http.StatusProxyAuthRequired}
	ErrRequestTimeout                = Error{"request time-out", http.StatusRequestTimeout}
	ErrConflict                      = Error{"conflict", http.StatusConflict}
	ErrGone                          = Error{"gone", http.StatusGone}
	ErrLengthRequired                = Error{"length required", http.StatusLengthRequired}
	ErrPreconditionFailed            = Error{"precondition failed", http.StatusPreconditionFailed}
	ErrRequestEntityTooLarge         = Error{"request entity too large", http.StatusRequestEntityTooLarge}
	ErrRequestURITooLong             = Error{"request URI too long", http.StatusRequestURITooLong}
	ErrUnsupportedMediaType          = Error{"unsupported media type", http.StatusUnsupportedMediaType}
	ErrRequestedRangeNotSatisfiable  = Error{"requested range unsatisfiable", http.StatusRequestedRangeNotSatisfiable}
	ErrExpectationFailed             = Error{"expectation failed", http.StatusExpectationFailed}
	ErrTeapot                        = Error{"i'm a teapot", http.StatusTeapot}
	ErrMisdirectedRequest            = Error{"misdirected request", http.StatusMisdirectedRequest}
	ErrUnprocessableEntity           = Error{"unprocessable entiy", http.StatusUnprocessableEntity}
	ErrLocked                        = Error{"locked", http.StatusLocked}
	ErrFailedDependency              = Error{"failed dependency", http.StatusFailedDependency}
	ErrTooEarly                      = Error{"too early", http.StatusTooEarly}
	ErrUpgradeRequired               = Error{"upgrade required", http.StatusUpgradeRequired}
	ErrPreconditionRequired          = Error{"precondition required", http.StatusPreconditionRequired}
	ErrTooManyRequests               = Error{"too many requests", http.StatusTooManyRequests}
	ErrRequestHeaderFieldsTooLarge   = Error{"request header fields too large", http.StatusRequestHeaderFieldsTooLarge}
	ErrUnavailableForLegalReasons    = Error{"unavailable for legal reasons", http.StatusUnavailableForLegalReasons}
	ErrInternalServer                = Error{"internal server error", http.StatusInternalServerError}
	ErrNotImplemented                = Error{"not implemented", http.StatusNotImplemented}
	ErrBadGateway                    = Error{"bad gateway", http.StatusBadGateway}
	ErrServiceUnavailable            = Error{"service unavailable", http.StatusServiceUnavailable}
	ErrGatewayTimeout                = Error{"gateway time-out", http.StatusGatewayTimeout}
	ErrHTTPVersionNotSupported       = Error{"http version not supported", http.StatusHTTPVersionNotSupported}
	ErrVariantAlsoNegotiates         = Error{"variant also negotiates", http.StatusVariantAlsoNegotiates}
	ErrInsufficientStorage           = Error{"insufficient storage", http.StatusInsufficientStorage}
	ErrLoopDetected                  = Error{"loop detected", http.StatusLoopDetected}
	ErrNotExtended                   = Error{"not extended", http.StatusNotExtended}
	ErrNetworkAuthenticationRequired = Error{"network authentication required", http.StatusNetworkAuthenticationRequired}
)

Functions

func CacheFileSystem

func CacheFileSystem(path string) (http.FileSystem, error)

func ErrFuncDefault

func ErrFuncDefault(w http.ResponseWriter, r *http.Request, err error)

func GetSympleError added in v0.1.2

func GetSympleError(err error) (error, int)

func NewRouter

func NewRouter(handler ErrorHandlerFunc) *routerState

Types

type ContentType

type ContentType string
const (
	ContentTypeTextPlain   ContentType = "text/plain"
	ContentTypeTextHtml    ContentType = "text/html"
	ContentTypeJson        ContentType = "application/json"
	ContentTypeXml         ContentType = "application/xml"
	ContentTypeFormEncoded ContentType = "application/x-www-form-urlencoded"
	ContentTypeFormData    ContentType = "multipart/form-data"
)

type Error added in v0.1.2

type Error struct {
	Message    string
	StatusCode int
}

func (Error) Error added in v0.1.2

func (e Error) Error() string

func (Error) Status added in v0.1.3

func (e Error) Status() int

type ErrorHandlerFunc

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

ErrorHandlerFunc is the function being called to handle HandlerFunc errors

type HandlerFunc

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

HandlerFunc is like http.HandlerFunc but returning an error

type HttpError added in v0.1.2

type HttpError interface {
	Error() string
	Status() int
}

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Jump to

Keyboard shortcuts

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