slow

package module
v0.0.0-...-ee1059d Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2023 License: BSD-3-Clause Imports: 31 Imported by: 0

README

Slow

See the Documentation


Simple Example

With a correctly configured Go toolchain:
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)

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

func GetFullPath

func GetFullPath() string

func MountSchemaFromRequest

func MountSchemaFromRequest(f *c3po.Fielder, req *Request) (reflect.Value, any)

func ServeFile

func ServeFile(ctx *Ctx, pathToFile ...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
	*Config
	// TODO -> add testConfig, ProdConfig
	AfterRequest,
	BeforeRequest,
	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(c *Config) *App

Returns a new app with a default settings

func (*App) Build

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)

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) TestCtx

func (app *App) TestCtx(req ...*http.Request) *Ctx

func (*App) UrlFor

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 Config

type Config struct {
	Env            string // environmnt
	SecretKey      string // for sign session
	Servername     string // for build url routes and route match
	ListeningInTLS bool   // UrlFor return a URl with schema in "https:"

	TemplateFolder string // for render Templates Html. Default "templates/"
	TemplateFuncs  template.FuncMap

	StaticFolder  string // for serve static files
	StaticUrlPath string // url uf request static file
	EnableStatic  bool   // enable static endpoint for serving static files

	Silent  bool   // don't print logs
	LogFile string // save log info in file

	SessionExpires          time.Duration
	SessionPermanentExpires time.Duration
}

func NewConfig

func NewConfig() *Config

func (*Config) Fields

func (c *Config) Fields() []string

func (*Config) GetField

func (c *Config) GetField(name string) (any, bool)

func (*Config) Set

func (c *Config) Set(name string, value any) bool

func (*Config) Update

func (c *Config) Update(cfg *Config)

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 {

	// Clone Current App
	App *App

	Global map[string]any

	Request  *Request  // Current Request
	Response *Response // Current Response

	// Current Cookie Session
	Session *Session

	// New Schema valid from route schema
	Schema        any
	SchemaFielder *c3po.Fielder

	// Contains information about the current request, route, etc...
	MatchInfo *MatchInfo
	// contains filtered or unexported fields
}

func (*Ctx) Next

func (ctx *Ctx) Next()

executes the next middleware or main function of the request

func (*Ctx) UrlFor

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

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

func (h *Header) Del(key string)

func (*Header) Get

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

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

Write the headers in the response

func (*Header) Set

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

Set a Header

func (*Header) SetCookie

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
	Route            *Route
	Router           *Router
	MethodNotAllowed error
}

type Meth

type Meth struct {
	Func
	Schema
	// contains filtered or unexported fields
}

type Middleware

type Middleware Func

type Middlewares

type Middlewares []Func

type Request

type Request struct {
	Header Header

	Body *bytes.Buffer
	Method,
	RemoteAddr,
	RequestURI,
	ContentType string

	ContentLength int

	URL     *url.URL
	Form    map[string]any
	Args    map[string]string
	Mime    map[string]string
	Query   url.Values
	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

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

func (*Request) Cancel

func (r *Request) Cancel()

Abort the current request. Server does not respond to client

func (*Request) Clone

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

func (*Request) Context

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

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

func (*Request) RawRequest

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

func (*Request) Referer

func (r *Request) Referer() string

func (*Request) RequestURL

func (r *Request) RequestURL() string

Returns the current url

func (*Request) UrlFor

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

func (r *Request) UserAgent() string

func (*Request) Websocket

func (r *Request) Websocket(headers http.Header) (*websocket.Conn, error)

func (*Request) WithContext

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

type Response

type Response struct {
	*bytes.Buffer

	StatusCode int

	Headers Header
	// contains filtered or unexported fields
}

func NewResponse

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

func (*Response) BadRequest

func (r *Response) BadRequest()

func (*Response) Close

func (r *Response) Close()

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

func (*Response) Created

func (r *Response) Created()

func (*Response) Forbidden

func (r *Response) Forbidden()

func (*Response) HTML

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

func (Response) Header

func (r Response) Header() http.Header

func (*Response) ImATaerpot

func (r *Response) ImATaerpot()

func (*Response) InternalServerError

func (r *Response) InternalServerError()

func (*Response) JSON

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

func (*Response) MethodNotAllowed

func (r *Response) MethodNotAllowed()

func (*Response) NoContent

func (r *Response) NoContent()

func (*Response) NotFound

func (r *Response) NotFound()

func (*Response) Ok

func (r *Response) Ok()

func (*Response) RawResponse

func (r *Response) RawResponse() http.ResponseWriter

func (*Response) Redirect

func (r *Response) Redirect(url string)

Redirect to Following URL

func (*Response) RenderTemplate

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

func (*Response) SetCookie

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

Set a cookie in the Headers of Response

func (*Response) TEXT

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

func (*Response) Unauthorized

func (r *Response) Unauthorized()

func (Response) Write

func (r Response) Write(b []byte) (int, error)

func (Response) WriteHeader

func (r Response) WriteHeader(statusCode int)

type Route

type Route struct {
	Url  string
	Name string

	Func    Func
	Methods []string

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

func Connect

func Connect(url string, f Func) *Route

func Delete

func Delete(url string, f Func) *Route

func Get

func Get(url string, f Func) *Route
func Head(url string, f Func) *Route

func Options

func Options(url string, f Func) *Route

func Patch

func Patch(url string, f Func) *Route

func Post

func Post(url string, f Func) *Route

func Put

func Put(url string, f Func) *Route

func Trace

func Trace(url string, f Func) *Route

func (*Route) GetRouter

func (r *Route) GetRouter() *Router

type Router

type Router struct {
	Name,
	Prefix,
	Subdomain string
	StrictSlash bool

	EnableSwagger bool

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

func NewRouter

func NewRouter(name string) *Router

func (*Router) Add

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

func (*Router) AddRoute

func (r *Router) AddRoute(route *Route)

func (*Router) AddRoutes

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

func (*Router) Connect

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

func (*Router) Delete

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

func (*Router) Get

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

func (*Router) Head

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

func (*Router) Options

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

func (*Router) Patch

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

func (*Router) Post

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

func (*Router) Put

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

func (*Router) Trace

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

Jump to

Keyboard shortcuts

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