diff --git a/README.md b/README.md index c13cbf60..c6218010 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ -Fiber

+

+ Fiber +

+

[![Latest Release](https://img.shields.io/github/release/fenny/fiber.svg)](https://github.com/fenny/fiber/releases/latest) [![GoDoc](https://godoc.org/github.com/fenny/fiber?status.svg)](http://godoc.org/github.com/fenny/fiber) diff --git a/context.go b/context.go index b4868e45..b3b7d2e2 100644 --- a/context.go +++ b/context.go @@ -1,9 +1,13 @@ package fiber import ( + "bytes" + "encoding/base64" "mime" "path/filepath" + "strings" + "github.com/pquerna/ffjson/ffjson" "github.com/valyala/fasthttp" ) @@ -42,6 +46,29 @@ func (ctx *Ctx) Path() string { return b2s(ctx.Fasthttp.URI().Path()) } +// BasicAuth : +func (ctx *Ctx) BasicAuth() (user, pass string, ok bool) { + auth := ctx.Get("Authorization") + if auth == "" { + return + } + const prefix = "Basic " + // Case insensitive prefix match. + if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { + return + } + c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) + if err != nil { + return + } + cs := string(c) + s := strings.IndexByte(cs, ':') + if s < 0 { + return + } + return cs[:s], cs[s+1:], true +} + // Body : func (ctx *Ctx) Body(args ...interface{}) string { if len(args) == 0 { @@ -148,6 +175,16 @@ func (ctx *Ctx) Get(key string) string { return b2s(ctx.Fasthttp.Request.Header.Peek(key)) } +// Json : +func (ctx *Ctx) Json(v interface{}) error { + ctx.Set("Content-Type", "application/json") + b := bytes.NewBuffer(nil) + enc := ffjson.NewEncoder(b) + err := enc.Encode(v) + ctx.Send(b.Bytes()) + return err +} + // Redirect : func (ctx *Ctx) Redirect(args ...interface{}) { if len(args) == 1 {