Skip to content

Commit

Permalink
Merge pull request #2 from gofiber/master
Browse files Browse the repository at this point in the history
add change
  • Loading branch information
codemicro committed Oct 21, 2020
2 parents 53ab7a6 + 25bb7d1 commit 12260c7
Show file tree
Hide file tree
Showing 19 changed files with 791 additions and 263 deletions.
2 changes: 1 addition & 1 deletion .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ When contributing to this repository, please first discuss the change you wish t

Please note: we have a [code of conduct](https://github.com/gofiber/fiber/blob/master/.github/CODE_OF_CONDUCT.md), please follow it in all your interactions with the `Fiber` project.

## Pull Requests or Comits
## Pull Requests or Commits
Titles always we must use prefix according to below:

> 🔥 Feature, ♻️ Refactor, 🩹 Fix, 🚨 Test, 📚 Doc, 🎨 Style
Expand Down
92 changes: 43 additions & 49 deletions .github/README_id.md

Large diffs are not rendered by default.

120 changes: 111 additions & 9 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import (
)

// Version of current fiber package
const Version = "2.0.6"
const Version = "2.1.0"

// Map is a shortcut for map[string]interface{}, useful for JSON returns
type Map map[string]interface{}
Expand Down Expand Up @@ -314,6 +314,13 @@ func New(config ...Config) *App {
if len(config) > 0 {
app.config = config[0]
}

if app.config.ETag {
if !IsChild() {
fmt.Println("[Warning] Config.ETag is deprecated since v2.0.6, please use 'middleware/etag'.")
}
}

// Override default values
if app.config.BodyLimit <= 0 {
app.config.BodyLimit = DefaultBodyLimit
Expand Down Expand Up @@ -693,15 +700,15 @@ func (app *App) startupMessage(addr string, tls bool, pids string) {
}

var logo string
logo += "\n%s"
logo += "%s"
logo += " ┌───────────────────────────────────────────────────┐\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ │\n"
logo += " │ Handlers %s Threads %s │\n"
logo += " │ Prefork .%s PID ....%s │\n"
logo += " └───────────────────────────────────────────────────┘"
logo += "%s\n\n"
logo += "%s"

const (
cBlack = "\u001b[90m"
Expand Down Expand Up @@ -751,6 +758,15 @@ func (app *App) startupMessage(addr string, tls bool, pids string) {
return str
}

pad := func(s string, width int) (str string) {
toAdd := width - len(s)
str += s
for i := 0; i < toAdd; i++ {
str += " "
}
return
}

host, port := parseAddr(addr)
if host == "" || host == "0.0.0.0" {
host = "127.0.0.1"
Expand All @@ -765,17 +781,103 @@ func (app *App) startupMessage(addr string, tls bool, pids string) {
isPrefork = "Enabled"
}

out := colorable.NewColorableStdout()
if os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
out = colorable.NewNonColorable(os.Stdout)
}
_, _ = fmt.Fprintf(out, logo,
mainLogo := fmt.Sprintf(logo,
cBlack,
centerValue(" Fiber v"+Version, 49),
center(addr, 49),
value(strconv.Itoa(app.handlerCount), 14), value(strconv.Itoa(runtime.NumCPU()), 14),
value(strconv.Itoa(app.handlerCount), 14), value(strconv.Itoa(runtime.GOMAXPROCS(0)), 14),
value(isPrefork, 14), value(strconv.Itoa(os.Getpid()), 14),
cReset,
)

var childPidsLogo string
if app.config.Prefork {
var childPidsTemplate string
childPidsTemplate += "%s"
childPidsTemplate += " ┌───────────────────────────────────────────────────┐\n%s"
childPidsTemplate += " └───────────────────────────────────────────────────┘"
childPidsTemplate += "%s"

newLine := " │ %s%s%s │"

// Turn the `pids` variable (in the form ",a,b,c,d,e,f,etc") into a slice of PIDs
var pidSlice []string
for _, v := range strings.Split(pids, ",") {
if v != "" {
pidSlice = append(pidSlice, v)
}
}

var lines []string
thisLine := "Child PIDs ... "
var itemsOnThisLine []string

addLine := func() {
lines = append(lines,
fmt.Sprintf(
newLine,
cBlack,
thisLine+cCyan+pad(strings.Join(itemsOnThisLine, ", "), 49-len(thisLine)),
cBlack,
),
)
}

for _, pid := range pidSlice {
if len(thisLine+strings.Join(append(itemsOnThisLine, pid), ", ")) > 49 {
addLine()
thisLine = ""
itemsOnThisLine = []string{pid}
} else {
itemsOnThisLine = append(itemsOnThisLine, pid)
}
}

// Add left over items to their own line
if len(itemsOnThisLine) != 0 {
addLine()
}

// Form logo
childPidsLogo = fmt.Sprintf(childPidsTemplate,
cBlack,
strings.Join(lines, "\n")+"\n",
cReset,
)
}

// Combine both the child PID logo and the main Fiber logo

// Pad the shorter logo to the length of the longer one
splitMainLogo := strings.Split(mainLogo, "\n")
splitChildPidsLogo := strings.Split(childPidsLogo, "\n")

mainLen := len(splitMainLogo)
childLen := len(splitChildPidsLogo)

if mainLen > childLen {
diff := mainLen - childLen
for i := 0; i < diff; i++ {
splitChildPidsLogo = append(splitChildPidsLogo, "")
}
} else {
diff := childLen - mainLen
for i := 0; i < diff; i++ {
splitMainLogo = append(splitMainLogo, "")
}
}

// Combine the two logos, line by line
output := "\n"
for i := range splitMainLogo {
output += cBlack + splitMainLogo[i] + " " + splitChildPidsLogo[i] + "\n"
}

out := colorable.NewColorableStdout()
if os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
out = colorable.NewNonColorable(os.Stdout)
}

fmt.Fprintln(out, output)

}
14 changes: 12 additions & 2 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type Ctx struct {
indexHandler int // Index of the current handler
method string // HTTP method
methodINT int // HTTP method INT equivalent
baseURI string // HTTP base uri
path string // Prettified HTTP path -> string copy from pathBuffer
pathBuffer []byte // Prettified HTTP path buffer
treePath string // Path for the search in the tree
Expand Down Expand Up @@ -94,6 +95,8 @@ func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx {
c.methodINT = methodInt(c.method)
// Attach *fasthttp.RequestCtx to ctx
c.fasthttp = fctx
// reset base uri
c.baseURI = ""
// Prettify path
c.prettifyPath()
return c
Expand Down Expand Up @@ -206,7 +209,11 @@ func (c *Ctx) Attachment(filename ...string) {
func (c *Ctx) BaseURL() string {
// TODO: Could be improved: 53.8 ns/op 32 B/op 1 allocs/op
// Should work like https://codeigniter.com/user_guide/helpers/url_helper.html
return c.Protocol() + "://" + c.Hostname()
if c.baseURI != "" {
return c.baseURI
}
c.baseURI = c.Protocol() + "://" + c.Hostname()
return c.baseURI
}

// Body contains the raw body submitted in a POST request.
Expand Down Expand Up @@ -904,6 +911,9 @@ var sendFileHandler fasthttp.RequestHandler
// The file is not compressed by default, enable this by passing a 'true' argument
// Sets the Content-Type response HTTP header field based on the filenames extension.
func (c *Ctx) SendFile(file string, compress ...bool) error {
// Save the filename, we will need it in the error message if the file isn't found
filename := file

// https://github.com/valyala/fasthttp/blob/master/fs.go#L81
sendFileOnce.Do(func() {
sendFileFS = &fasthttp.FS{
Expand Down Expand Up @@ -953,7 +963,7 @@ func (c *Ctx) SendFile(file string, compress ...bool) error {
}
// Check for error
if status != StatusNotFound && fsStatus == StatusNotFound {
return fmt.Errorf("sendfile: file %s not found", file)
return NewError(StatusNotFound, fmt.Sprintf("sendfile: file %s not found", filename))
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ func Test_Ctx_BaseURL(t *testing.T) {
utils.AssertEqual(t, "http://google.com", c.BaseURL())
}

// go test -v -run=^$ -bench=Benchmark_Ctx_Append -benchmem -count=4
// go test -v -run=^$ -bench=Benchmark_Ctx_BaseURL -benchmem
func Benchmark_Ctx_BaseURL(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
Expand Down Expand Up @@ -1309,7 +1309,7 @@ func Test_Ctx_SendFile_404(t *testing.T) {
app.Get("/", func(c *Ctx) error {
err := c.SendFile("./john_dow.go/")
utils.AssertEqual(t, false, err == nil)
return nil
return err
})

resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ go 1.14

require (
github.com/valyala/fasthttp v1.16.0
golang.org/x/sys v0.0.0-20200929083018-4d22bbb62b3c
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211
)
10 changes: 6 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
github.com/andybalholm/brotli v1.0.0 h1:7UCwP93aiSfvWpapti8g88vVVGp2qqtGyePsSuDafo4=
github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc=
github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/klauspost/compress v1.10.7 h1:7rix8v8GpI3ZBb0nSozFRgbtXKv+hOe+qfEpZqybrAg=
github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.11.0 h1:wJbzvpYMVGG9iTI9VxpnNZfd4DzMPoCWze3GgSqz8yg=
github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.11.1 h1:bPb7nMRdOZYDrpPMTA3EInUQrdgoBinqUuSwlGdKDdE=
github.com/klauspost/compress v1.11.1/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.16.0 h1:9zAqOYLl8Tuy3E5R6ckzGDJ1g8+pw15oQp2iL9Jl6gQ=
Expand All @@ -19,7 +21,7 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20u
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y=
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200929083018-4d22bbb62b3c h1:/h0vtH0PyU0xAoZJVcRw1k0Ng+U0JAy3QDiFmppIlIE=
golang.org/x/sys v0.0.0-20200929083018-4d22bbb62b3c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211 h1:9UQO31fZ+0aKQOFldThf7BKPMJTiBfWycGh/u3UoO88=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
55 changes: 30 additions & 25 deletions middleware/basicauth/basicauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,32 +110,37 @@ func New(config Config) fiber.Handler {
// Get authorization header
auth := c.Get(fiber.HeaderAuthorization)

// Check if header is valid
if len(auth) > 6 && strings.ToLower(auth[:5]) == "basic" {

// Try to decode
if raw, err := base64.StdEncoding.DecodeString(auth[6:]); err == nil {

// Convert to string
cred := utils.UnsafeString(raw)

// Find semicolumn
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// Split into user & pass
user := cred[:i]
pass := cred[i+1:]

// If exist & match in Users, we let him pass
if cfg.Authorizer(user, pass) {
c.Locals(cfg.ContextUsername, user)
c.Locals(cfg.ContextPassword, pass)
return c.Next()
}
}
}
}
// Check if the header contains content besides "basic".
if len(auth) <= 6 || strings.ToLower(auth[:5]) != "basic" {
return cfg.Unauthorized(c)
}

// Decode the header contents
raw, err := base64.StdEncoding.DecodeString(auth[6:])
if err != nil {
return cfg.Unauthorized(c)
}

// Get the credentials
creds := utils.UnsafeString(raw)

// Check if the credentials are in the correct form
// which is "username:password".
index := strings.Index(creds, ":")
if index == -1 {
return cfg.Unauthorized(c)
}

// Get the username and password
username := creds[:index]
password := creds[index+1:]

if cfg.Authorizer(username, password) {
c.Locals(cfg.ContextUsername, username)
c.Locals(cfg.ContextPassword, password)
return c.Next()
}

// Authentication failed
return cfg.Unauthorized(c)
}
Expand Down
10 changes: 5 additions & 5 deletions middleware/basicauth/basicauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (

// go test -run Test_BasicAuth_Next
func Test_BasicAuth_Next(t *testing.T) {
t.Parallel()

app := fiber.New()
app.Use(New(Config{
Next: func(_ *fiber.Ctx) bool {
Expand All @@ -28,16 +30,15 @@ func Test_BasicAuth_Next(t *testing.T) {
}

func Test_Middleware_BasicAuth(t *testing.T) {
t.Parallel()
app := fiber.New()

cfg := Config{
app.Use(New(Config{
Users: map[string]string{
"john": "doe",
"admin": "123456",
},
}

app.Use(New(cfg))
}))

app.Get("/testauth", func(c *fiber.Ctx) error {
username := c.Locals("username").(string)
Expand Down Expand Up @@ -85,7 +86,6 @@ func Test_Middleware_BasicAuth(t *testing.T) {
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, tt.statusCode, resp.StatusCode)

// Only check body if statusCode is 200
if tt.statusCode == 200 {
utils.AssertEqual(t, fmt.Sprintf("%s%s", tt.username, tt.password), string(body))
}
Expand Down

0 comments on commit 12260c7

Please sign in to comment.