braza

package module
v0.0.0-...-54e7c99 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: BSD-3-Clause Imports: 35 Imported by: 0

README

braza

See the Documentation

Features

- File Watcher (in development mode)
- Error management
- Router
- Schema Validator (converts the form into a Struct - c3po package)
- Rendering built-in (template/html)
- Endpoints
- Implements net/http

- Supports
    Jwt 
    Cors 
    Sessions
    Websocket
    Middleware & Next
    URL Route builder

Simple Example

With a correctly configured Go toolchain:
go get github.com/ethoDomingues/braza

main.go

package main

import "github.com/ethoDomingues/braza"

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

 fmt.Println(app.Listen())
}

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

func helloUser(ctx *braza.Ctx) {
 rq := ctx.Request   // current Request
 name := rq.Args["name"]
 ctx.HTML("<h1>Hello "+name+"</h1>", 200)
}

func userByID(ctx *braza.Ctx) {
 rq := ctx.Request   // current Request
 id := rq.Args["userID"]
 user := AnyQuery(id)
 ctx.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 MountSchemaFromRequest

func MountSchemaFromRequest(f *c3po.Fielder, rq *Request) (any, error)

func RestarSelf

func RestarSelf()

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

	BasicAuth func(*Ctx) (user string, pass string, ok bool) // custom func to parse Authorization Header
	AfterRequest,
	BeforeRequest,
	TearDownRequest Func // exec after each request, after send to cleint ( this dont has effect in response)

	Srv *http.Server
	// contains filtered or unexported fields
}

func NewApp

func NewApp(cfg *Config) *App

Create 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 braza.Ctx){}

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

func (*App) Clone

func (app *App) Clone() *App

Create a clone of app. obs: changes to the application do not affect the clone

func (*App) ErrorHandler

func (app *App) ErrorHandler(statusCode int, f Func)

func (*App) Listen

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

func (*App) ListenTLS

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

func (*App) Mount

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

Register the router in app

func main() {
	api := braza.NewRouter("api")
	api.post("/products")
	api.get("/products/{productID:int}")

	app := braza.NewApp(nil)

	app.Mount(getApiRouter)
	app.Listen()
}

func (*App) ServeHTTP

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

http.Handler

func (*App) ShowRoutes

func (app *App) ShowRoutes()

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"}) //  /users/1
app.UrlFor("index", true, "userID", "1"}) // http://yourAddress/users/1

type Config

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

	TemplateFolder   string // for render Templates Html. Default "templates/"
	TemplateFuncs    template.FuncMap
	TemplateReloader bool // if app in dev mode, allow template's reload (default true)

	StaticFolder  string // for serve static files (default '/assets')
	StaticUrlPath string // url uf request static file (default '/assets')
	DisableStatic bool   // disable static endpoint for serving static files (default false)

	Silent             bool   // don't print logs (default false)
	LogFile            string // save log info in file (default ”)
	DisableFileWatcher bool   // disable autoreload in dev mode (default false)

	SessionExpires          time.Duration // (default 30 minutes)
	SessionPermanentExpires time.Duration // (default 31 days)
	// contains filtered or unexported fields
}

func NewConfig

func NewConfig() *Config

Usage:

env := "dev"
devConfig := braza.NewConfig()
prodConfig := braza.NewConfig()
var cfg  *Config

if env == "dev"{
	cfg = devConfig
} else {
	cfg = prodConfig
}
app := braza.NewApp(cfg)
...

func (*Config) SetupFromFile

func (c *Config) SetupFromFile(filename string) error

type Cors

type Cors struct {
	MaxAge           string   // Access-Control-Max-Age
	AllowOrigins     []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
	// contains filtered or unexported fields
}

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

type Ctx

type Ctx struct {
	App     *App           // Clone Current App
	Global  map[string]any // global variables of current request
	Session *Session       // Current Cookie Session

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

	// New Schema valid from route schema
	Schema        Schema
	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 *Ctx)

func Handler

func Handler(h http.Handler) Func
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 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) Clone

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

func (*Request) Context

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

func (*Request) Ctx

func (r *Request) Ctx() *Ctx

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 *braza.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() (*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) Abort

func (r *Response) Abort(code int)

func (*Response) BadRequest

func (r *Response) BadRequest()

func (*Response) CheckErr

func (r *Response) CheckErr(err error)

func (*Response) Close

func (r *Response) Close()

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

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

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

func (r *Response) Redirect(url string)

Redirect to Following URL

func (*Response) RenderTemplate

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

func (*Response) ServeFile

func (r *Response) ServeFile(ctx *Ctx, pathToFile string)

Serve File

func (*Response) SetCookie

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

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      Schema
	MapCtrl     MapCtrl
	Middlewares Middlewares

	IsStatic bool
	// 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

func (*Route) MountURI

func (r *Route) MountURI(args ...string) string

type Router

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

	Cors        *Cors
	Routes      []*Route
	Middlewares []Func

	WsUpgrader *websocket.Upgrader
	// 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(routes ...*Route)

func (*Router) AllMethods

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

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

example:

type User struct{
	Name string `braza:"name=name"`
	Email string `braza:"name=user,in=auth"`
	Password string `braza:"name=password,in=auth"`
	ProfilePhoto *braza.File `braza:"name=img,in=files"`
	KeepConnected bool `braza:"name=keep,inquery"`
}

func AnyHandler(ctx *braza.Ctx){
	u, ok := ctx.Schema.(*User)
	...
}

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

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

func (*Session) String

func (s *Session) String() string

Directories

Path Synopsis
examples
api

Jump to

Keyboard shortcuts

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