SexPistol

Sex

import "github.com/Plankiton/SexPistol"

Index

Constants

const (
    LogLevelInfo  = "\033[32;1m[info] \033[00m"
    LogLevelWarn  = "\033[33;1m[warn] \033[00m"
    LogLevelError = "\033[31;1m[fail] \033[00m"
)
const (
    StatusContinue           = 100
    StatusSwitchingProtocols = 101
    StatusProcessing         = 102
    StatusEarlyHints         = 103

    StatusOK                   = 200
    StatusCreated              = 201
    StatusAccepted             = 202
    StatusNonAuthoritativeInfo = 203
    StatusNoContent            = 204
    StatusResetContent         = 205
    StatusPartialContent       = 206
    StatusMultiStatus          = 207
    StatusAlreadyReported      = 208
    StatusIMUsed               = 226

    StatusMultipleChoices  = 300
    StatusMovedPermanently = 301
    StatusFound            = 302
    StatusSeeOther         = 303
    StatusNotModified      = 304
    StatusUseProxy         = 305

    StatusTemporaryRedirect = 307
    StatusPermanentRedirect = 308

    StatusBadRequest                   = 400
    StatusUnauthorized                 = 401
    StatusPaymentRequired              = 402
    StatusForbidden                    = 403
    StatusNotFound                     = 404
    StatusMethodNotAllowed             = 405
    StatusNotAcceptable                = 406
    StatusProxyAuthRequired            = 407
    StatusRequestTimeout               = 408
    StatusConflict                     = 409
    StatusGone                         = 410
    StatusLengthRequired               = 411
    StatusPreconditionFailed           = 412
    StatusRequestEntityTooLarge        = 413
    StatusRequestURITooLong            = 414
    StatusUnsupportedMediaType         = 415
    StatusRequestedRangeNotSatisfiable = 416
    StatusExpectationFailed            = 417
    StatusTeapot                       = 418
    StatusMisdirectedRequest           = 421
    StatusUnprocessableEntity          = 422
    StatusLocked                       = 423
    StatusFailedDependency             = 424
    StatusTooEarly                     = 425
    StatusUpgradeRequired              = 426
    StatusPreconditionRequired         = 428
    StatusTooManyRequests              = 429
    StatusRequestHeaderFieldsTooLarge  = 431
    StatusUnavailableForLegalReasons   = 451

    StatusInternalServerError           = 500
    StatusNotImplemented                = 501
    StatusBadGateway                    = 502
    StatusServiceUnavailable            = 503
    StatusGatewayTimeout                = 504
    StatusHTTPVersionNotSupported       = 505
    StatusVariantAlsoNegotiates         = 506
    StatusInsufficientStorage           = 507
    StatusLoopDetected                  = 508
    StatusNotExtended                   = 510
    StatusNetworkAuthenticationRequired = 511
)

func Byteify

func Byteify(v interface{}) []byte

Byteify encode variable into JSON encoded byte array

func Copy

func Copy(source interface{}, destine interface{}) error

Copy provides util to copy map or struct to another map or struct Required: Destine need to be a pointer Example: var m struct { Name string `json:”name”` } j := Dict{ “name”: “Joao”\, } Sex.Copy(j\, &m)

func Debug

func Debug(v ...interface{})

Debuging stdout display

func Die

func Die(args ...interface{})

Die logs error logs with Sex.Logger() and kill application

func Dief

func Dief(args ...interface{})

Dief logs error with Sex.Logger() and killing the application Example: Dief(“%s %+v”\, “joao”\, []string{“joao”\, “maria”}) Dief(”%.2f”\, 409.845)

func Err

func Err(args ...interface{})

Err logs error logs with Sex.Logger()

func Errf

func Errf(args ...interface{})

Errf logs error formated with Sex.Logger() Example: Errf(“%s %+v”\, “joao”\, []string{“joao”\, “maria”}) Errf(”%.2f”\, 409.845)

func Fmt

func Fmt(s string, v ...interface{}) string

Fmt provides formated string

func GetEnv

func GetEnv(key string, def string) string

GetEnv function thats get a environment var or default value if var does not exist

func GetPathPattern

func GetPathPattern(t string) string

GetPathPattern provides regex pattern of a Sex path template Example: Sex.GetPathPattern(“/hello/{name}”)

func IndexOf

func IndexOf(i interface{}, l interface{}) int

IndexOf function to index first ocurrence of thing in thing slice

func Jsonify

func Jsonify(encoded []byte, v interface{}) error

Jsonify decode JSON encoded byte array into variable Required: v needs to be a pointer

func Log

func Log(args ...interface{})

Log logs information logs with Sex.Logger()

func Logf

func Logf(args ...interface{})

Logf logs information formated logs with Sex.Logger() Example: Logf(“%s %+v”\, “joao”\, []string{“joao”\, “maria”}) Logf(”%.2f”\, 409.845)

func Merge

func Merge(source interface{}, destine interface{}, override ...bool) (interface{}, error)

Merge provides util to merge map or struct to another map or struct Required: Destine need to be a pointer Example: var m := struct { Name string `json:”name”` } { Name: “Joao”\, } j := Dict{ “idade”: “Joao”\, “name”: nil\, } f := Sex.Merge(m\, &j)

Merge rules: If the field on source dont exists on destine it will be created (just if destine are map) If the field on source exists on destine but are dont seted it will be seted If the field on source exists on destine but are seted it will not be seted If override are seted as true\, the field on destine will be overrided by source

func RawLog

func RawLog(typ string, useCaller bool, args ...interface{})

RawLog logs a raw log

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

func Stringify

func Stringify(v interface{}) string

Stringify encode variable into JSON encoded string

func UseLogger

func UseLogger(l *Logger)

UseLogger sets SexPistol logger

func War

func War(args ...interface{})

War logs warning logs with Sex.Logger()

func Warf

func Warf(args ...interface{})

Warf logs warning formated with Sex.Logger() Example: Warf(“%s %+v”\, “joao”\, []string{“joao”\, “maria”}) Warf(”%.2f”\, 409.845)

type Bullet

Suggested template for Sex.Json endpoint functions

type Bullet struct {
    Message string      `json:"message,omitempty"`
    Type    string      `json:"type,omitempty"`
    Data    interface{} `json:"data,omitempty"`
}

type Config

Config is group of properties (Prop)

type Config map[string]Prop

type Dict

Dict is dictionary key:value\, but key is always string

type Dict map[string]interface{}

type Json

Json Sex type for json format endpoint outputs

type Json interface{}

type Logger

type Logger struct {
    log.Logger
}

func NewLogger

func NewLogger() *Logger

NewLogger provides new SexPistol logger

type Pistol

Pistol is the Sex HTTP handler\, who are used to setup http server Example: router := Sex.NewPistol(). Add(”/”\, func(Sex.Request) string { return “Hello World” }). Run()

type Pistol struct {
    *http.ServeMux
    // contains filtered or unexported fields
}

func NewPistol

func NewPistol() *Pistol

NewPistol create new Sex.Pistol and default configurations Example: router := Sex.NewPistol()

func (*Pistol) Add

func (pistol *Pistol) Add(path string, route interface{}, methods ...string) *Pistol

Add adds endpoint to the Sex.Pistol Server path are the endpoint location route is a void interface thats need to be on next format list: - func (http.ResponseWriter\, *http.Request) - func (Sex.Request) Sex.Response (res\, status) - func (Sex.Request) string // Or (string\, int) - func (Sex.Request) []byte // Or ([]byte\, int) - func (Sex.Request) Sex.Json // Or (Sex.Json\, int) methods are a list of accepted HTTP methods to endpoint Example: router.Add(”/”\, func(Sex.Request) string { return “Hello World” }\, “POST”) router.Add(“/ok”\, func(Sex.Request) Sex.Json\, int { return map[stirng]bool{ “ok”: true\, }\, 404 })

func (*Pistol) AddPlugin

func (pistol *Pistol) AddPlugin(plugin Plugin) *Pistol

AddPlugin adds plugins to Sex Pistol

func (*Pistol) Error

func (pistol *Pistol) Error() error

Error provides Pistol last error

func (*Pistol) GetPath

func (pistol *Pistol) GetPath() string

GetPath provides Pistol root path

func (*Pistol) GetRoutes

func (pistol *Pistol) GetRoutes() Dict

GetRoutes provides Pistol route list

func (*Pistol) Run

func (pistol *Pistol) Run(a ...interface{}) error

Run set-up Sex.Pistol server Example: pistol.Run(5000) // Will run server on port 5000 pistol.Run(“/joao”) // will run server on path “/joao” pistol.Run(“/joao”\, 80) // will run server on path “/joao” and port 80 pistol.Run(80\, “/joao”) // will run server on path “/joao” and port 80

If you run a Sex Pistol server with $SEX_DEBUG setted as “true” thats function will to log list all Sex endpoints of router

func (*Pistol) ServeHTTP

func (pistol *Pistol) ServeHTTP(w http.ResponseWriter, r *http.Request)

Function to make Sex.Pistol a http.Handler

func (*Pistol) SetErr

func (pistol *Pistol) SetErr(err error)

SetErr sets Pistol last error

type Plugin

Plugin is a extension to Sex Pistol

type Plugin interface {
    Name() string
    Init(*Pistol) (*Pistol, error)
    Root(http.ResponseWriter, *http.Request) (http.ResponseWriter, *http.Request)
}

type Prop

Prop are map of properties

type Prop map[string][]string

func GetPathVars

func GetPathVars(t string, p string) (Prop, error)

GetPathVars provides path variables a Sex path template Example: Sex.GetPathVars(“/hello/{name}”\, “/hello/joao”)

func (Prop) Add

func (h Prop) Add(key, value string)

Add adds the key\, value pair to the header. It appends to any existing values associated with key. The key is case sensitive.

func (Prop) Del

func (h Prop) Del(key string)

Del deletes the values associated with key. The key is case sensitive.

func (Prop) Get

func (h Prop) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key\, Get returns “”. It is case sensitive.

func (Prop) Has

func (h Prop) Has(key string) bool

Has reports whether h has the provided key defined\, even if it’s set to 0-length slice.

func (Prop) Set

func (h Prop) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key and value is case sensitive.

func (Prop) Values

func (h Prop) Values(key string) []string

Values returns all values associated with the given key. It is case sensitive

type Request

Request is the request sent by client (*http.Request) with inproviments like path variables and Pistol Route configurations Example: router.Add(“/hello/{name}”\, func (r Sex.Request) string { name := r.PathVars[“name”] return “Hello “+ name }

type Request struct {
    http.Request
    PathVars Prop
    Conf     Prop
}

func NewRequest

func NewRequest() *Request

NewRequest create new Request

func (*Request) Json

func (r *Request) Json(v interface{}) error

JSON provides marshalled Json body to a variable Example: var data map[string]interface{} // Can be Structs too r.JsonBody(&data)

func (*Request) Raw

func (r *Request) Raw(b *[]byte) error

Raw provides byte array body to a variable Example: var data []byte r.Raw(&data)

type Response

Response to make complete response with Cookies\, Headers\, and all http.ResponseWrite another features

type Response struct {
    http.ResponseWriter
    Headers *http.Header
    Body    []byte
    Status  int
    // contains filtered or unexported fields
}

func NewResponse

func NewResponse() *Response

NewResponse provides new Response

func (*Response) Error

func (r *Response) Error() error

Error provides Pistol last error

func (*Response) Header

func (r *Response) Header() http.Header

Header returns response headers setter

func (*Response) SetBody

func (r *Response) SetBody(v []byte) *Response

SetBody sets Response body

func (*Response) SetCookie

func (r *Response) SetCookie(key string, value string, expires time.Duration) *Response

SetCookie sets Response cookies

func (*Response) SetErr

func (r *Response) SetErr(err error)

SetErr sets Pistol last error

func (*Response) SetStatus

func (r *Response) SetStatus(code int) *Response

SetStatus sets Response status code

func (*Response) WriteHeader

func (r *Response) WriteHeader(status int)

WriteHeader sets Response status code

Generated by gomarkdoc