slow

package module
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2023 License: BSD-3-Clause Imports: 30 Imported by: 11

README

Slow

See the Documentation


Simple Example

Com a correta configuração do go
go get github.com/ethoDomingues/slow

main.go

package main

import "github.com/ethodomingues/slow"

func main() {
 app := slow.NewApp()
 app.Get("/hello", helloWorld)
 app.Get("/hello/{name}", helloUser) // 'name' is any string
 app.Get("/hello/{userID:int}", userByID) // 'userID' is only int

 app.Listen()
}

func helloWorld(ctx *slow.Ctx) {
 rsp := ctx.Response
 hello := map[string]any{"Hello": "World"}
 rsp.JSON(hello, 200)
}

func helloUser(ctx *slow.Ctx) {
 rq := ctx.Request   // current Request
 rsp := ctx.Response // current Response

 name := rq.Args["name"]
 rsp.HTML("Hello "+name, 200)
}
func userByID(ctx *slow.Ctx) {
 rq := ctx.Request   // current Request
 rsp := ctx.Response // current Response

 id := rq.Args["userID"]
 user := AnyQuery(id)
 rsp.JSON(user, 200)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrHttpAbort        = errors.New("aborted")
	ErrorNotFound       = errors.New("404 Not Found")
	ErrorMethodMismatch = errors.New("405 Method Not Allowed")
)

Functions

func Abort

func Abort(code int)

Stops execution, cleans up the response body, and writes the StatusCode to the response

func GetFullPath added in v0.0.9

func GetFullPath() string

func HtmlEscape

func HtmlEscape(s string) string

func SignJWT

func SignJWT(headers, payload map[string]string, secret string) string

func TypeOf

func TypeOf(obj any) string

Alias of 'fmt.Sprintf("%T", obj)'

Types

type App

type App struct {
	*Router

	Env            string // environmnt
	LogFile        string // save log info in file
	SecretKey      string // for sign session
	Servername     string // for build url routes and route match
	StaticFolder   string // for serve static files
	StaticUrlPath  string // url uf request static file
	TemplateFolder string // for render template (html) files

	Silent         bool // don't print logs
	EnableStatic   bool // enable static endpoint for serving static files
	ListeningInTLS bool // UrlFor return a URl with schema in "https:"

	BeforeRequest,
	AfterRequest,
	TearDownRequest Func // exec after each request, after send to cleint ( this dont has effect in response)
	// contains filtered or unexported fields
}

func NewApp

func NewApp() *App

Returns a new app with a default settings

func (*App) Build added in v0.0.9

func (app *App) Build(addr ...string)

Build the App, but not start serve

example:

func index(ctx slow.Ctx){}

// it's work
func main() {
	app := slow.NewApp()
	app.GET("/",index)
	app.Build(":5000")
	app.UrlFor("index",true)
}
// it's don't work
func main() {
	app := slow.NewApp()
	app.GET("/",index)
	app.UrlFor("index",true)
}

func (*App) Listen

func (app *App) Listen(host ...string) error

Build a app and starter Server

func (*App) ListenTLS added in v0.0.9

func (app *App) ListenTLS(certFile string, keyFile string, host ...string) error

Build a app and starter Server

func (*App) Mount

func (app *App) Mount(routers ...*Router)

Register the router in app

func main() {
	api := slow.NewRouter("api")
	api.Subdomain = "api"
	api.Prefix = "/v1"
	api.post("/products")
	api.get("/products/{productID:int}")

	app := slow.NewApp()

	// This Function
	app.Mount(getApiRouter)

	app.Listen()
}

func (*App) ServeHTTP

func (app *App) ServeHTTP(wr http.ResponseWriter, req *http.Request)

http.Handler func

func (*App) ShowRoutes

func (app *App) ShowRoutes()

Show All Routes

func (*App) UrlFor added in v0.0.9

func (app *App) UrlFor(name string, external bool, args ...string) string

Url Builder

app.GET("/users/{userID:int}", index)

app.UrlFor("index", false, "userID", "1"})
// results: /users/1

app.UrlFor("index", true, "userID", "1"})
// results: http://yourAddress/users/1

type Cors

type Cors struct {
	MaxAge           string   // Access-Control-Max-Age
	AllowOrigin      string   // Access-Control-Allow-Origin
	AllowMethods     []string // Access-Control-Allow-Methods
	AllowHeaders     []string // Access-Control-Allow-Headers
	ExposeHeaders    []string // Access-Control-Expose-Headers
	RequestMethod    string   // Access-Control-Request-Method
	AllowCredentials bool     // Access-Control-Allow-Credentials
}

If present on route or router, allows resource sharing between origins

type Ctx

type Ctx struct {

	// Current App
	App *App

	Global map[string]any

	// Current Request
	Request *Request

	// Current Response
	Response *Response

	Session *Session

	// Contains information about the current request and the route
	MatchInfo *MatchInfo
}

func (*Ctx) UrlFor added in v0.0.11

func (ctx *Ctx) UrlFor(name string, external bool, args ...string) string

type File

type File struct {
	Filename     string
	ContentType  string
	ContentLeght int
	Stream       *bytes.Buffer
}

func NewFile

func NewFile(p *multipart.Part) *File

type Func

type Func func(*Ctx)
type Header http.Header

func (*Header) Add added in v0.0.11

func (h *Header) Add(key string, value string)

Add value in a in Header Key. If the key does not exist, it is created

func (*Header) Del added in v0.0.11

func (h *Header) Del(key string)

func (*Header) Get added in v0.0.11

func (h *Header) Get(key string) string

Return a value of Header Key. If the key does not exist, return a empty string

func (*Header) Save added in v0.0.11

func (h *Header) Save(w http.ResponseWriter)

Write the headers in the response

func (*Header) Set added in v0.0.11

func (h *Header) Set(key string, value string)

Set a Header

func (*Header) SetCookie added in v0.0.11

func (h *Header) SetCookie(cookie *http.Cookie)

Set a Cookie. Has the same effect as 'Response.SetCookie'

type JWT

type JWT struct {
	Headers, Payload map[string]string
	Secret           string
}

func NewJWT

func NewJWT(secret string) *JWT

func ValidJWT

func ValidJWT(jwt, secret string) (*JWT, bool)

func (*JWT) Sign

func (j *JWT) Sign() string

type MapCtrl

type MapCtrl map[string]*Meth

type MatchInfo

type MatchInfo struct {
	Func

	Match            bool
	MethodNotAllowed error

	Route  *Route
	Router *Router
	// contains filtered or unexported fields
}

type Meth

type Meth struct {
	Func
	Method string
	Schema
}

type Methods

type Methods []string

type Middlewares

type Middlewares []Func

func NewMiddleware

func NewMiddleware(f ...Func) Middlewares

type Request

type Request struct {
	Header Header

	Body,
	Method,
	RemoteAddr,
	RequestURI,
	ContentType string

	ContentLength int

	URL     *url.URL
	Form    map[string]any
	Args    map[string]string
	Mime    map[string]string
	Query   map[string][]string
	Files   map[string][]*File
	Cookies map[string]*http.Cookie

	TransferEncoding []string

	Proto      string // "HTTP/1.0"
	ProtoMajor int    // 1
	ProtoMinor int    // 0
	// contains filtered or unexported fields
}

func NewRequest

func NewRequest(req *http.Request, ctx *Ctx) *Request

func (*Request) BasicAuth added in v0.0.11

func (r *Request) BasicAuth() (username, password string, ok bool)

func (*Request) Cancel added in v0.0.2

func (r *Request) Cancel()

Abort the current request. Server does not respond to client

func (*Request) Clone added in v0.0.11

func (r *Request) Clone(ctx context.Context) *Request

func (*Request) Context added in v0.0.2

func (r *Request) Context() context.Context

Returns a 'context.Context' of the current request

func (*Request) Ctx

func (r *Request) Ctx() *Ctx

Returns a '*slow.Ctx' of the current request

func (*Request) ProtoAtLeast added in v0.0.11

func (r *Request) ProtoAtLeast(major, minor int) bool

func (*Request) RawRequest added in v0.0.11

func (r *Request) RawRequest() *http.Request

func (*Request) Referer added in v0.0.11

func (r *Request) Referer() string

func (*Request) RequestURL

func (r *Request) RequestURL() string

Returns the current url

func (*Request) UrlFor added in v0.0.9

func (r *Request) UrlFor(name string, external bool, args ...string) string

URL Builder

app.GET("/", index)
app.GET("/login", login)

app.UrlFor("login", false, "next", "currentUrl"})
// results: /login?next=currentUrl

app.UrlFor("login", true, "token", "foobar"})
// results: http://yourAddress/login?token=foobar

// example
func index(ctx *slow.Ctx) {
	req := ctx.Request
	rsp := ctx.Response
	userID, ok := ctx.Global["user"]
	if !ok {
		next := r.RequestUrl()
		rsp.Redirect(req.UrlFor("login", true, "next", next))
		//  redirect to: http://youraddress/login?next=http://yourhost:port/
	}
	... you code here
}

func (*Request) UserAgent added in v0.0.11

func (r *Request) UserAgent() string

func (*Request) WithContext added in v0.0.11

func (r *Request) WithContext(ctx context.Context) *Request

type Response

type Response struct {
	StatusCode int

	Body   *bytes.Buffer
	Header Header
	// contains filtered or unexported fields
}

func NewResponse

func NewResponse(wr http.ResponseWriter, ctx *Ctx) *Response

func (*Response) BadRequest

func (r *Response) BadRequest(body ...any)

Send a BadRequest ( Status and Text )

func (*Response) Close

func (r *Response) Close()

Halts execution and closes the "response". This does not clear the response body

func (*Response) Forbidden

func (r *Response) Forbidden(body ...any)

Send a StatusForbidden ( Status and Text )

func (*Response) HTML

func (r *Response) HTML(body string, code int)

func (*Response) ImATaerpot

func (r *Response) ImATaerpot(body ...any)

Send a StatusImATaerpot ( Status and Text )

func (*Response) InternalServerError

func (r *Response) InternalServerError(body ...any)

Send a StatusInternalServerError ( Status and Text )

func (*Response) JSON

func (r *Response) JSON(body any, code int)

func (*Response) MethodNotAllowed

func (r *Response) MethodNotAllowed(body ...any)

Send a StatusMethodNotAllowed ( Status and Text )

func (*Response) NotFound

func (r *Response) NotFound(body ...any)

Send a StatusNotFound ( Status and Text )

func (*Response) Ok

func (r *Response) Ok(body ...any)

Send a StatusOk ( Status and Text )

func (*Response) Redirect

func (r *Response) Redirect(url string)

Redirect to Following URL

func (*Response) RenderTemplate

func (r *Response) RenderTemplate(pathToFile string, data ...any)

Parse Html file and send to client

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

Set a cookie in the Headers of Response

func (*Response) TEXT added in v0.0.9

func (r *Response) TEXT(body string, code int)

func (*Response) Unauthorized

func (r *Response) Unauthorized(body ...any)

Send a Unauthorized ( Status and Text )

type Route

type Route struct {
	Url     string
	Name    string
	Func    Func
	MapCtrl MapCtrl

	Cors        *Cors
	Schema      any
	Methods     Methods
	Middlewares Middlewares
	// contains filtered or unexported fields
}

func ALL added in v0.0.9

func ALL(url string, f Func) *Route

func CONNECT added in v0.0.6

func CONNECT(url string, f Func) *Route

func DELETE added in v0.0.6

func DELETE(url string, f Func) *Route

func GET added in v0.0.6

func GET(url string, f Func) *Route
func HEAD(url string, f Func) *Route

func OPTIONS added in v0.0.6

func OPTIONS(url string, f Func) *Route

func PATCH added in v0.0.6

func PATCH(url string, f Func) *Route

func POST added in v0.0.6

func POST(url string, f Func) *Route

func PUT added in v0.0.6

func PUT(url string, f Func) *Route

func TRACE added in v0.0.6

func TRACE(url string, f Func) *Route

type Router

type Router struct {
	Name,
	Prefix,
	Subdomain string

	Cors        *Cors
	Routes      []*Route
	Middlewares Middlewares
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(name string) *Router

func (*Router) ALL added in v0.0.9

func (r *Router) ALL(url string, f Func)

func (*Router) Add

func (r *Router) Add(url, name string, f Func, meths []string)

func (*Router) AddAll

func (r *Router) AddAll(routes ...*Route)

func (*Router) CONNECT added in v0.0.2

func (r *Router) CONNECT(url string, f Func)

func (*Router) DELETE added in v0.0.6

func (r *Router) DELETE(url string, f Func)

func (*Router) GET added in v0.0.6

func (r *Router) GET(url string, f Func)

func (*Router) HEAD added in v0.0.2

func (r *Router) HEAD(url string, f Func)

func (*Router) OPTIONS added in v0.0.2

func (r *Router) OPTIONS(url string, f Func)

func (*Router) PATCH added in v0.0.2

func (r *Router) PATCH(url string, f Func)

func (*Router) POST added in v0.0.6

func (r *Router) POST(url string, f Func)

func (*Router) PUT added in v0.0.6

func (r *Router) PUT(url string, f Func)

func (*Router) TRACE added in v0.0.2

func (r *Router) TRACE(url string, f Func)

type Schema

type Schema any

type Session

type Session struct {
	Permanent bool
	// contains filtered or unexported fields
}

func (*Session) Del

func (s *Session) Del(key string)

Delete a Value from Session

func (*Session) Get

func (s *Session) Get(key string) (string, bool)

Returns a session value based on the key. If key does not exist, returns an empty string

func (*Session) GetSign

func (s *Session) GetSign() string

Returns a JWT Token from session data

func (*Session) Set

func (s *Session) Set(key, value string)

This inserts a value into the session

Directories

Path Synopsis
routing module

Jump to

Keyboard shortcuts

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