MakyuuIchaival/httputils/fasthttp.go

132 lines
2.9 KiB
Go

package httputils
import (
"bytes"
"fmt"
"github.com/valyala/fasthttp"
"io"
"time"
)
var fsHandler = (&fasthttp.FS{
Root: "/",
AcceptByteRange: true,
Compress: false,
CompressBrotli: false,
CacheDuration: time.Minute * 15,
PathRewrite: func(ctx *fasthttp.RequestCtx) []byte {
return ctx.Request.URI().PathOriginal()
},
}).NewRequestHandler()
type FastHTTPContext struct {
ctx *fasthttp.RequestCtx
server *Server
connTime time.Time
requestTime time.Time
timingEvents uint
}
func NewRequestContextFromFastHttp(server *Server, ctx *fasthttp.RequestCtx) *FastHTTPContext {
if ctx == nil {
return nil
}
return &FastHTTPContext{
ctx: ctx,
connTime: ctx.ConnTime(),
requestTime: ctx.Time(),
server: server,
}
}
func (c *FastHTTPContext) GetExtraHeaders() map[string]string {
return c.server.GetExtraHeaders()
}
func (c *FastHTTPContext) AddTiming(name string, desc string, d time.Duration) {
if d < 0 {
d = 0
}
c.AddResponseHeader("Server-Timing", fmt.Sprintf("%d_%s;desc=\"%s\";dur=%.6F", c.timingEvents, name, desc, float64(d.Nanoseconds())/1e6))
c.timingEvents++
}
func (c *FastHTTPContext) AddTimingInformational(name string, desc string) {
c.AddResponseHeader("Server-Timing", fmt.Sprintf("%d_%s;desc=\"%s\"", c.timingEvents, name, desc))
c.timingEvents++
}
func (c *FastHTTPContext) GetPath() string {
return string(c.ctx.Path())
}
func (c *FastHTTPContext) GetConnectionTime() time.Time {
return c.connTime
}
func (c *FastHTTPContext) GetRequestTime() time.Time {
return c.requestTime
}
func (c *FastHTTPContext) GetTLSServerName() string {
return c.ctx.TLSConnectionState().ServerName
}
func (c *FastHTTPContext) GetRequestHeader(name string) string {
return string(c.ctx.Request.Header.Peek(name))
}
func (c *FastHTTPContext) GetResponseHeader(name string) string {
return string(c.ctx.Response.Header.Peek(name))
}
func (c *FastHTTPContext) AddResponseHeader(name string, value string) {
c.ctx.Response.Header.Add(name, value)
}
func (c *FastHTTPContext) SetResponseHeader(name string, value string) {
c.ctx.Response.Header.Set(name, value)
}
func (c *FastHTTPContext) ServeFile(path string) {
c.ctx.Request.URI().Reset()
c.ctx.Request.URI().SetPath(path)
fsHandler(c.ctx)
}
func (c *FastHTTPContext) ServeBytes(content []byte) {
c.ctx.Write(content)
}
func (c *FastHTTPContext) SetResponseCode(code int) {
c.ctx.Response.SetStatusCode(code)
}
func (c *FastHTTPContext) DoRedirect(location string, code int) {
c.ctx.Redirect(location, code)
}
func (c *FastHTTPContext) GetBody() io.Reader {
b := c.ctx.Request.Body()
buf := make([]byte, len(b))
copy(buf, b)
return bytes.NewBuffer(buf)
}
func (c *FastHTTPContext) IsGet() bool {
return c.ctx.IsGet()
}
func (c *FastHTTPContext) IsPost() bool {
return c.ctx.IsPost()
}
func (c *FastHTTPContext) IsOptions() bool {
return c.ctx.IsOptions()
}
func (c *FastHTTPContext) IsHead() bool {
return c.ctx.IsHead()
}