MakyuuIchaival/httputils/nethttp.go

125 lines
2.6 KiB
Go

package httputils
import (
"fmt"
"io"
"net/http"
"time"
)
type NetHTTPContext struct {
httpWriter http.ResponseWriter
httpRequest *http.Request
server *Server
connTime time.Time
requestTime time.Time
timingEvents uint
}
func NewRequestContextFromHttp(server *Server, w http.ResponseWriter, r *http.Request) *NetHTTPContext {
return &NetHTTPContext{
httpWriter: w,
httpRequest: r,
connTime: time.Now(),
requestTime: time.Now(),
server: server,
}
}
func (c *NetHTTPContext) GetExtraHeaders() map[string]string {
return c.server.GetExtraHeaders()
}
func (c *NetHTTPContext) 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 *NetHTTPContext) AddTimingInformational(name string, desc string) {
c.AddResponseHeader("Server-Timing", fmt.Sprintf("%d_%s;desc=\"%s\"", c.timingEvents, name, desc))
c.timingEvents++
}
func (c *NetHTTPContext) GetPath() string {
return c.httpRequest.URL.Path
}
func (c *NetHTTPContext) GetConnectionTime() time.Time {
return c.connTime
}
func (c *NetHTTPContext) GetRequestTime() time.Time {
return c.requestTime
}
func (c *NetHTTPContext) GetTLSServerName() string {
return c.httpRequest.TLS.ServerName
}
func (c *NetHTTPContext) GetRequestHeader(name string) string {
return c.httpRequest.Header.Get(name)
}
func (c *NetHTTPContext) GetResponseHeader(name string) string {
return c.httpWriter.Header().Get(name)
}
func (c *NetHTTPContext) AddResponseHeader(name string, value string) {
c.httpWriter.Header().Add(name, value)
}
func (c *NetHTTPContext) SetResponseHeader(name string, value string) {
c.httpWriter.Header().Set(name, value)
}
func (c *NetHTTPContext) ServeFile(path string) {
http.ServeFile(c.httpWriter, c.httpRequest, path)
}
func (c *NetHTTPContext) ServeBytes(content []byte) {
c.httpWriter.Write(content)
}
func (c *NetHTTPContext) SetResponseCode(code int) {
c.httpWriter.WriteHeader(code)
}
func (c *NetHTTPContext) DoRedirect(location string, code int) {
http.Redirect(c.httpWriter, c.httpRequest, location, code)
}
func (c *NetHTTPContext) GetBody() io.Reader {
return c.httpRequest.Body
}
func (c *NetHTTPContext) IsGet() bool {
return c.httpRequest.Method == "GET"
}
func (c *NetHTTPContext) IsPost() bool {
return c.httpRequest.Method == "POST"
}
func (c *NetHTTPContext) IsOptions() bool {
return c.httpRequest.Method == "OPTIONS"
}
func (c *NetHTTPContext) IsHead() bool {
return c.httpRequest.Method == "HEAD"
}