Documentation
¶
Index ¶
- Variables
- func Daemon(apps ...*App) error
- func MountSchemaFromRequest(f *c3po.Fielder, rq *Request) c3po.Schema
- func SetCookie(h http.Header, cookie *http.Cookie)
- func SetHeader(w http.ResponseWriter, h http.Header)
- func TypeOf(obj any) string
- type App
- func (app *App) Build(addr ...string)
- func (app *App) ErrorHandler(statusCode int, f Func)
- func (app *App) Listen(host ...string) (err error)
- func (app *App) ListenTLS(certFile, certKey string, host ...string) (err error)
- func (app *App) Mount(routers ...*Router)
- func (app *App) ServeHTTP(wr http.ResponseWriter, req *http.Request)
- func (app *App) ShowRoutes()
- func (app *App) UrlFor(name string, external bool, args ...string) string
- type Config
- type Cors
- type Ctx
- type File
- type Func
- type Jsonify
- type ManyJsonify
- type ManyMapper
- type MapCtrl
- type Mapper
- type MatchInfo
- type Meth
- type Request
- func (r *Request) BasicAuth() (username, password string, ok bool)
- func (r *Request) Clone(ctx context.Context) *Request
- func (r *Request) Context() context.Context
- func (r *Request) Ctx() *Ctx
- func (r *Request) HttpRequest() *http.Request
- func (r *Request) ParseForm()
- func (r *Request) ProtoAtLeast(major, minor int) bool
- func (r *Request) Referer() string
- func (r *Request) RequestURL() string
- func (r *Request) UrlFor(name string, external bool, args ...string) string
- func (r *Request) UserAgent() string
- func (r *Request) Websocket() (*websocket.Conn, error)
- func (r *Request) WithContext(ctx context.Context) *Request
- type RespSchema
- type Response
- func (r *Response) Abort(code int)
- func (r *Response) BadRequest()
- func (r *Response) CheckErr(err error)
- func (r *Response) Close()
- func (r *Response) Created()
- func (r *Response) Forbidden()
- func (r *Response) HTML(body any, code int)
- func (r Response) Header() http.Header
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) ImATaerpot()
- func (r *Response) InternalServerError()
- func (r *Response) JSON(body any, code int)
- func (r *Response) MethodNotAllowed()
- func (r *Response) NoContent()
- func (r *Response) NotFound()
- func (r *Response) Ok()
- func (r *Response) Redirect(url string)
- func (r *Response) RenderTemplate(tmpl string, data ...any)
- func (r *Response) ServeFile(pathToFile string)
- func (r *Response) SetCookie(cookie *http.Cookie)
- func (r Response) SetHeader(h http.Header)
- func (r *Response) TEXT(body any, code int)
- func (r *Response) Unauthorized()
- func (r Response) Write(b []byte) (int, error)
- func (r Response) WriteHeader(statusCode int)
- type Route
- func CONNECT(url string, f Func) *Route
- func DELETE(url string, f Func) *Route
- func GET(url string, f Func) *Route
- func HEAD(url string, f Func) *Route
- func OPTIONS(url string, f Func) *Route
- func PATCH(url string, f Func) *Route
- func POST(url string, f Func) *Route
- func PUT(url string, f Func) *Route
- func TRACE(url string, f Func) *Route
- type Router
- func (r *Router) Add(url, name string, f Func, meths []string)
- func (r *Router) AddRoute(routes ...*Route)
- func (r *Router) CONNECT(url string, f Func)
- func (r *Router) DELETE(url string, f Func)
- func (r *Router) GET(url string, f Func)
- func (r *Router) HEAD(url string, f Func)
- func (r *Router) OPTIONS(url string, f Func)
- func (r *Router) PATCH(url string, f Func)
- func (r *Router) POST(url string, f Func)
- func (r *Router) PUT(url string, f Func)
- func (r *Router) TRACE(url string, f Func)
- type Schema
- type Session
Constants ¶
This section is empty.
Variables ¶
Functions ¶
Types ¶
type App ¶
type App struct {
// Main Router
*Router
// Main Config
*Config
/*
custom auth parser
app.BasicAuth = (ctx *braza.Ctx) {
a := ctx.Request.Header.Get("Authorization")
if a != ""{
...
return user,pass, true
}
return "","",false
}
*/
BasicAuth func(*Ctx) (user string, pass string, ok bool) // custom func to parse Authorization Header
/*
exec after each request (if the application dont crash)
app.AfterRequest = (ctx *braza.Ctx) {
h := ctx.Response.Header()
h.Set("X-Foo","Bar")
ctx.Response.SetHeader(h)
...
}
*/
AfterRequest Func
/*
exec before each request
app.BeforeRequest = (ctx *braza.Ctx) {
db := database.Open()
ctx.Global["db"] = db
user,pass,ok := ctx.Request.BasicAuth()
if ok {
ctx.Global["user"] = user
}
}
*/
BeforeRequest Func
/*
exec after close each conn ( this dont has effect in response)
app.TearDownRequest = (ctx *braza.Ctx) {
database.Close()
log.Print(...)
...
}
*/
TearDownRequest Func
// The Http.Server
Srv *http.Server
// contains filtered or unexported fields
}
func NewApp ¶
Create a new app with a default settings
app := NewApp(nil) // or NewApp(*braza.Config{})
...
app.Listen()
func (*App) Build ¶
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()
app.UrlFor("index",true)
}
// it's don't work
func main() {
app := braza.NewApp()
app.GET("/",index)
app.UrlFor("index",true)
}
func (*App) ErrorHandler ¶
Custom Http Error Handler
app.ErrorHandler(401,(ctx *braza.Ctx) {
ctx.HTML("Access denied",401)
})
app.ErrorHandler(404,(ctx *braza.Ctx) {
ctx.HTML("Hey boy, you're a little lost",404)
})
func (*App) Mount ¶
Register Router in app
func main() {
api := braza.NewRouter("api")
api.post("/products")
api.get("/products/{productID:int}")
app := braza.NewApp(nil)
app.Mount(api)
// do anything ...
app.Listen()
}
func (*App) ServeHTTP ¶
func (app *App) ServeHTTP(wr http.ResponseWriter, req *http.Request)
http.Handler
func (*App) ShowRoutes ¶
func (app *App) ShowRoutes()
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 `validate:"-"`
DisableParseFormBody bool // Disable default parse of Request.Form -> if true, use Request.ParseForm()
DisableTemplateReloader bool // if app in dev mode, disable template's reload (default false)
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)
DisableWarnOn405 bool
LogFile string // save log info in file (default ”)
DisableFileWatcher bool // disable autoreload in dev mode (default false)
SessionExpires time.Duration `validate:"-"` // (default 30 minutes)
SessionPermanentExpires time.Duration `validate:"-"` // (default 31 days)
SessionPublicKey *rsa.PublicKey `validate:"-"`
SessionPrivateKey *rsa.PrivateKey `validate:"-"`
// 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 NewConfigFromFile ¶
func (*Config) SetupFromFile ¶
setup config from json, yalm
type Cors ¶
type Cors struct {
MaxAge string // Access-Control-Max-Age
// ex:
// []string{"example.com","www.example.com"}
AllowOrigins []string // Access-Control-Allow-Origin
// ex:
// []string{"*","GET","POST"}
AllowMethods []string // Access-Control-Allow-Methods
// ex:
// []string{"Authorization","*"}
AllowHeaders []string // Access-Control-Allow-Headers
// ex:
// []string{"X-Header"}
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 {
// Clone Current App
App *App
/*
global variables of current request
app.BeforeRequest = (ctx *braza.Ctx){
db := database.Open().Session()
ctx.Global["db"] = db
user := db.FindUser()
ctx.Global["user"] = user
}
func index(ctx *braza.Ctx){
db := ctx.Global["db"].(database.DB)
user := ctx.Global["user"].(*User)
...
}
*/
Global map[string]any
/*
Current Cookie Session
func login(ctx *braza.Ctx){
db := ctx.Global["db"].(database.DB)
username,pass,ok := ctx.Request.BasicAuth()
if ok{
user := &User{}
db.Where("username = ?",username).Find(user)
if user.CompareHashPass(pass){
ctx.Session.Set("user",user.id)
}
}
ctx.Unauthorized()
}
*/
Session *Session
/*
Current Response
func foo(ctx *braza.Ctx) {
ctx.JSON(map[string]any{
"foo":"bar",
}, 200)
}
func foo(ctx *braza.Ctx) {
ctx.HTML("<h1>Hello</h1>",200)
}
func foo(ctx *braza.Ctx) {
ctx.RenderTemplate("index.html")
}
*/
*Response
/*
Current Request
*/
Request *Request
/*
New Schema valid from route schema
Route{
Url:"/{foo}/{bar:int}"
Func: foo,
Schema: &Schema{}
}
type Schema struct {
Bar int `braza:"in=args"`
Foo string `braza:"in=args"`
File *braza.File `braza:"in=files"`
Files []*braza.File `braza:"in=files"`
XHeader string `braza:"in=headers"`
User string `braza:"in=auth,name=username"`
Pass string `braza:"in=auth,name=password"`
Limit int `braza:"in=query"` // /path/search?limit=1&offset=2
Offset int `braza:"in=query"` // /path/search?limit=1&offset=2
Text string `braza:"in=body"`
Text2 string // deafult is 'in=body'.
}
func foo(ctx *braza.Ctx) {
sch := ctx.Schema.(*Schema)
...
}
*/
Schema Schema
SchemaFielder *c3po.Fielder
/*
Contains information about the current request, route, etc...
Can only be accessed if there is a match. otherwise the values will be null
func xpto(ctx *braza.Ctx) {
route := ctx.Matchinfo.Route
router := ctx.Matchinfo.Router
...
}
*/
MatchInfo *MatchInfo
// contains filtered or unexported fields
}
type ManyJsonify ¶
type ManyJsonify[C Jsonify] []C
func (ManyJsonify[C]) ToJson ¶
func (mj ManyJsonify[C]) ToJson() any
type ManyMapper ¶
func (ManyMapper[C]) ToMap ¶
func (mm ManyMapper[C]) ToMap() []map[string]any
type Meth ¶
type Meth struct {
Func Func
Schema Schema
RespSchema RespSchema
SchemaFielder *c3po.Fielder
}
type Request ¶
type Request struct {
Header http.Header
Body *bytes.Buffer
Method,
RemoteAddr,
RequestURI,
ContentType string
ContentLength int
URL *url.URL
Host string
Port string
Form map[string]any
PathArgs 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 (*Request) HttpRequest ¶
func (*Request) ProtoAtLeast ¶
func (*Request) UrlFor ¶
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
}
type RespSchema ¶
type Response ¶
func NewResponse ¶
func NewResponse(wr http.ResponseWriter, ctx *Ctx) *Response
func NewResponseForTest ¶
func (*Response) BadRequest ¶
func (r *Response) BadRequest()
func (*Response) ImATaerpot ¶
func (r *Response) ImATaerpot()
func (*Response) InternalServerError ¶
func (r *Response) InternalServerError()
func (*Response) MethodNotAllowed ¶
func (r *Response) MethodNotAllowed()
func (*Response) RenderTemplate ¶
func (*Response) Unauthorized ¶
func (r *Response) Unauthorized()
func (Response) WriteHeader ¶
type Route ¶
type Route struct {
/*
# url patterns
"" is same "/"
"/batata" // match literal "/batata"
"/{name}" // match any string (ex: batata1234)
"/{id:int}" // match on numbers (ex: 12345)
"/{path:*}" || "/{path:path}" // match anything
"/{var1:int}/{var2}/{var3}" // is allowed
`/(\d+)` // regex work too
*/
Url string
// # Route Name
// ctx.UrlFor("route Name"...
Name string
Func Func
/*
allow Cors on this route
&Cors{
AllowOrigins: []string{"example.com","www.example.com"},
AllowMethods: []string{"*","GET","POST"},
AllowHeaders: []string{"Authorization","*"},
ExposeHeaders: []string{"X-Header"},
AllowCredentials: true
}
*/
Cors *Cors
Schema Schema
RespSchema RespSchema
/*
# a peculiar way of establishing routes
Route{
Name:"foo",
Url:"/foo",
MapCtrl: braza.MapCtrl{
"GET": &braza.Meth{
Func: Foo,
Schema: &SchemaFoo{}
},
"POST": &braza.Meth{
Func: Bar,
Schema: &SchemaBar{}
},
"DELETE": &braza.Meth{
Func: Xpto,
Schema: &SchemaXpto{}
},
},
}
*/
MapCtrl MapCtrl
// HTTP methods allowed on this route
// []string{"GET","POST","PATCH",...
Methods []string
// Func wiil exec before this route
// []Func{ GetUser, HasAUth,...
Middlewares []Func
// contains filtered or unexported fields
}
type Router ¶
type Schema ¶
type Schema any
example:
type Schema struct {
Bar int `braza:"in=args"`
File *braza.File `braza:"in=files"`
Files []*braza.File `braza:"in=files"`
XHeader string `braza:"in=headers"`
User string `braza:"in=auth,name=username"`
Pass string `braza:"in=auth,name=password"`
Limit int `braza:"in=query"` // /path/search?limit=1&offset=2
Offset int `braza:"in=query"` // /path/search?limit=1&offset=2
Text string `braza:"in=body"`
Text2 string // deafult is 'in=body'.
}
Route{
Name:"foo",
Url:"/{bar:int}",
Schema: &Schema{},
}
func AnyHandler(ctx *braza.Ctx){
u := ctx.Schema.(*Schema)
...
}
Source Files
¶
Click to show internal directories.
Click to hide internal directories.