zhttp: github.com/zgoat/zhttp Index | Files | Directories

package zhttp

import "github.com/zgoat/zhttp"


Package Files

auth.go decode.go flash.go handlers.go headers.go ratelimit.go reqlog.go route.go secret.go serve.go static.go tpl.go tplfunc.go unpanic.go util.go wrap.go


const (
    ContentUnsupported uint8 = iota
const (
    LevelInfo  = "i"
    LevelError = "e"

Level constants.

const (
    // Don't set any header.
    CacheNoHeader = 0

    // Set to "no-cache" to tell browsers to always validate a cache (with e.g.
    // If-Match or If-None-Match). It does NOT tell browsers to never store a
    // cache; use Cache NoStore for that.
    CacheNoCache = -1

    // Set to "no-store, no-cache" to tell browsers to never store a local copy
    // (the no-cache is there to be sure previously stored copies from before
    // this header are revalidated).
    CacheNoStore = -2

Constants for the NewStatic() cache parameter.


var DefaultHeaders = http.Header{
    "Strict-Transport-Security": []string{"max-age=2592000"},
    "X-Frame-Options":           []string{"deny"},
    "X-Content-Type-Options":    []string{"nosniff"},

DefaultHeaders will be set by default.

var ErrPage = DefaultErrPage
var FuncMap = template.FuncMap{
    "deref_s":      TderefS,
    "unsafe":       Tunsafe,
    "unsafe_js":    TunsafeJS,
    "checked":      Tchecked,
    "nformat":      Tnformat,
    "tformat":      Ttformat,
    "mult":         Tmult,
    "sum":          Tsum,
    "div":          Tdiv,
    "sub":          Tsub,
    "if2":          Tif2,
    "has_prefix":   ThasPrefix,
    "has_suffix":   ThasSuffix,
    "option_value": ToptionValue,
    "checkbox":     Tcheckbox,
    "pp":           Tpp,

FuncMap contains all the template functions.

var Static404 = func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, fmt.Sprintf("packed file not found: %q", r.RequestURI), 404)
var TplPath = "tpl"

TplPath is the path to template files.

func Auth Uses

func Auth(load loadFunc) func(http.Handler) http.Handler

func Bytes Uses

func Bytes(w http.ResponseWriter, b []byte) error

func ClearCookie Uses

func ClearCookie(w http.ResponseWriter)

func Decode Uses

func Decode(r *http.Request, dst interface{}) (uint8, error)

Decode request parameters from a form, JSON body, or query parameters.

Returns one of the Content* constants, which is useful if you want to alternate the responses.

func DefaultErrPage Uses

func DefaultErrPage(w http.ResponseWriter, r *http.Request, code int, reported error)

TODO: make it easy to hide errors on production.

func ErrorCode Uses

func ErrorCode(err error) string

ErrorCode gets a hash based on the error value.

func ExecuteTpl Uses

func ExecuteTpl(name string, data interface{}) ([]byte, error)

ExecuteTpl executes a named template.

func Filter Uses

func Filter(f filterFunc) func(http.Handler) http.Handler

Filter access to a resource.

If the returning error is a github.com/teamwork/guru.coder and has a redirect code, then the error value is used as a redirection.

func Flash Uses

func Flash(w http.ResponseWriter, msg string, v ...interface{})

Flash sets a new flash message at the LevelInfo, overwriting any previous messages (if any).

func FlashError Uses

func FlashError(w http.ResponseWriter, msg string, v ...interface{})

FlashError sets a new flash message at the LevelError, overwriting any previous messages (if any).

func HandlerCSP Uses

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

HandlerCSP handles CSP errors.

func HandlerRobots Uses

func HandlerRobots(rules [][]string) func(w http.ResponseWriter, r *http.Request)

HandlerRobots writes a simple robots.txt.

func Headers Uses

func Headers(h http.Header) func(next http.Handler) http.Handler

Headers sets the given headers.

DefaultHeaders will always be set. Headers passed to this function overrides them. Use a nil value to remove a header.

func HostRoute Uses

func HostRoute(routers map[string]chi.Router) http.HandlerFunc

HostRoute redirects requests to chi.Routers based on the Host header.

The routers can be simple domain names ("example.com", "foo.example.com") or with a leading wildcard ("*.example.com", "*.foo.example.com").

func InitTpl Uses

func InitTpl(pack map[string][]byte)

InitTpl sets up the templates.

func JSON Uses

func JSON(w http.ResponseWriter, i interface{}) error

func Log Uses

func Log(host bool, timeFmt string, ignore ...string) func(http.Handler) http.Handler

func MountACME Uses

func MountACME(r chi.Router, certdir string)

HandlerACME adds a handler to respond to http-01 verifications.

func MovedPermanently Uses

func MovedPermanently(w http.ResponseWriter, url string) error

MovedPermanently redirects to the given URL.

func NewTpl Uses

func NewTpl() *template.Template

func Ratelimit Uses

func Ratelimit(
    keyFunc func(*http.Request) string,
    store RatelimitStore,
    perPeriod, periodSeconds int,
) func(http.Handler) http.Handler

Ratelimit requests.

Visitors are identified by a "key". This is usually the IP address or user ID.

perPeriod is the number of API calls (to all endpoints) that can be made by the client before receiving a 429 error

func RatelimitIP Uses

func RatelimitIP(r *http.Request) string

RatelimitIP rate limits based IP address.

Assumes RemoteAddr is set correctly. E.g. with chi's middleware.RealIP middleware.

func RedirectHost Uses

func RedirectHost(dst string) chi.Router

RedirectHost redirects all requests to the destination host.

Mainly intended for redirecting "example.com" to "www.example.com", or vice verse. The full URL is preserved, so "example.com/a?x is redirected to www.example.com/a?x

Only GET requests are redirected.

func ReloadTpl Uses

func ReloadTpl()

ReloadTpl reloads the templates.

func RemovePort Uses

func RemovePort(host string) string

RemovePort removes the "port" part of an hostname.

This only works for "host:port", and not URLs. See net.SplitHostPort.

func Secret Uses

func Secret() string

Secret number of 256 bits formatted in base36.

func SecretP Uses

func SecretP() *string

SecretP is like Secret() but returns a pointer.

func SeeOther Uses

func SeeOther(w http.ResponseWriter, url string) error

SeeOther redirects to the given URL.

"A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred by the server over HTTP. However, the Location field value refers to a resource that is descriptive of the target resource, such that making a retrieval request on that other resource might result in a representation that is useful to recipients without implying that it represents the original target resource."

func Serve Uses

func Serve(server *http.Server, wait func())

Serve a HTTP server with graceful shutdown.

func SetCookie Uses

func SetCookie(w http.ResponseWriter, val, domain string)

func String Uses

func String(w http.ResponseWriter, s string) error

func Tcheckbox Uses

func Tcheckbox(current bool, name string) template.HTML

Tcheckbox adds a checkbox; if current is true then it's checked.

It also adds a hidden input with the value "off" so that's sent to the server when the checkbox isn't sent, which greatly simplifies backend handling.

func Tchecked Uses

func Tchecked(vals []int64, id int64) template.HTMLAttr

Tchecked returns a 'checked="checked"' attribute if id is in vals.

func TderefS Uses

func TderefS(s *string) string

TderefS dereferences a string pointer, returning "" if it's nil.

func Tdiv Uses

func Tdiv(n, n2 int, n3 ...float32) float32

Tdiv divides all the given numbers.

func Template Uses

func Template(w http.ResponseWriter, name string, data interface{}) error

func ThasPrefix Uses

func ThasPrefix(s, prefix string) bool

ThasPrefix tests whether the string s begins with prefix.

func ThasSuffix Uses

func ThasSuffix(s, suffix string) bool

ThasSuffix tests whether the string s ends with suffix.

func Tif2 Uses

func Tif2(cond bool, yes, no interface{}) interface{}

Tif2 returns yes if cond is true, and no otherwise.

func Tmult Uses

func Tmult(n, n2 int, n3 ...int) int

Tmult multiplies all the given numbers.

func Tnformat Uses

func Tnformat(n int) string

Tnformat formats a number with thousand separators.

func ToptionValue Uses

func ToptionValue(current, value string) template.HTMLAttr

ToptionValue inserts the value attribute, and selected attribute if the value is the same as current.

func Tpp Uses

func Tpp(v interface{}) string

Tpp pretty-prints any object.

func Tsub Uses

func Tsub(n, n2 int, n3 ...int) int

Tsub substracts all the given numbers.

func Tsum Uses

func Tsum(n, n2 int, n3 ...int) int

Tsum sums all the given numbers.

func Ttformat Uses

func Ttformat(t time.Time, fmt string) string

Tdformat formats a time as the given format string.

func Tunsafe Uses

func Tunsafe(s string) template.HTML

Tunsafe converts a string to template.HTML, preventing any escaping.

Can be dangerous if used on untrusted input!

func TunsafeJS Uses

func TunsafeJS(s string) template.JS

TunsafeJS converts a string to template.JS, preventing any escaping.

Can be dangerous if used on untrusted input!

func Unpanic Uses

func Unpanic(prod bool) func(http.Handler) http.Handler

TODO: https://github.com/Teamwork/middleware/blob/master/rescue/rescue.go

func Wrap Uses

func Wrap(handler HandlerFunc) http.HandlerFunc

Wrap a http.HandlerFunc

type CSPError Uses

type CSPError struct {
    Report Report `json:"csp-report"`

CSP errors.

type FlashMessage Uses

type FlashMessage struct {
    Level   string
    Message template.HTML

FlashMessage is a displayed flash message.

func ReadFlash Uses

func ReadFlash(w http.ResponseWriter, r *http.Request) *FlashMessage

ReadFlash reads any existing flash message, returning the severity level and the message itself.

type HandlerFunc Uses

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

HandlerFunc function.

type RatelimitMemory Uses

type RatelimitMemory struct {
    // contains filtered or unexported fields

RatelimitMemory rate limits requests based on IP address, and stores the rate limit information in the Go process' memory.

func NewRatelimitMemory Uses

func NewRatelimitMemory() *RatelimitMemory

func (*RatelimitMemory) Grant Uses

func (m *RatelimitMemory) Grant(key string, perPeriod int, duration int64) (bool, int)

type RatelimitStore Uses

type RatelimitStore interface {
    Grant(key string, perPeriod int, duration int64) (granted bool, remaining int)

type Report Uses

type Report struct {
    BlockedURI   string `json:"blocked-uri"`
    ColumnNumber int    `json:"column-number"`
    DocumentURI  string `json:"document-uri"`
    LineNumber   int    `json:"line-number"`
    Referrer     string `json:"referrer"`
    SourceFile   string `json:"source-file"`
    Violated     string `json:"violated-directive"`

CSP errors.

type Static Uses

type Static struct {
    // contains filtered or unexported fields

Static file server.

func NewStatic Uses

func NewStatic(dir, domain string, cache int, packed map[string][]byte) Static

NewStatic returns a new static fileserver.

It will serve all files in dir. Symlinks are followed (even outside of dir!), but paths containing ".." are not allowed.

The domain parameter is used for CORS.

Cache is set to the Cache-Control: max-age parameter, or use one of the special Cache* constants.

If packed is not nil then all files will be served from the map, and the filesystem is never accessed. This is useful for self-contained production builds.

func (Static) ServeHTTP Uses

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

type User Uses

type User interface {
    GetToken() string


zmailPackage zmail is a simple mail sender.

Package zhttp imports 30 packages (graph). Updated 2019-12-13. Refresh now. Tools for package owners.