🚨 extract func quoteString() for ctx.Attachment and ctx.Download

pull/596/head
kiyon 2020-07-13 12:37:50 +08:00
parent 5a85ab072f
commit 9d9cfa8424
3 changed files with 12 additions and 7 deletions

9
ctx.go
View File

@ -197,12 +197,7 @@ func (ctx *Ctx) Attachment(filename ...string) {
fname := filepath.Base(filename[0])
ctx.Type(filepath.Ext(fname))
bb := bytebufferpool.Get()
bb.SetString(`attachment; filename="`)
b := fasthttp.AppendQuotedArg(bb.B, getBytes(fname))
b = append(b, '"')
ctx.Set(HeaderContentDisposition, string(b))
bytebufferpool.Put(bb)
ctx.Set(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
return
}
ctx.Set(HeaderContentDisposition, "attachment")
@ -352,7 +347,7 @@ func (ctx *Ctx) Download(file string, filename ...string) error {
if len(filename) > 0 {
fname = filename[0]
}
ctx.Set(HeaderContentDisposition, "attachment; filename="+fname)
ctx.Set(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
return ctx.SendFile(file)
}

View File

@ -933,6 +933,7 @@ func Test_Ctx_Download(t *testing.T) {
expect, err := ioutil.ReadAll(f)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, expect, ctx.Fasthttp.Response.Body())
utils.AssertEqual(t, `attachment; filename="Awesome+File%21"`, string(ctx.Fasthttp.Response.Header.Peek(HeaderContentDisposition)))
}
// go test -race -run Test_Ctx_SendFile

View File

@ -7,6 +7,8 @@ package fiber
import (
"bytes"
"fmt"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
"hash/crc32"
"net"
"strings"
@ -15,6 +17,13 @@ import (
utils "github.com/gofiber/utils"
)
func quoteString(raw string) string {
bb := bytebufferpool.Get()
quoted := string(fasthttp.AppendQuotedArg(bb.B, getBytes(raw)))
bytebufferpool.Put(bb)
return quoted
}
// Scan stack if other methods match
func setMethodNotAllowed(ctx *Ctx) {
var matched bool