Documentation
¶
Overview ¶
Package ahttp is to cater HTTP helper methods for aah framework. Like parse HTTP headers, ResponseWriter, content type, etc.
Index ¶
- Constants
- Variables
- func Dir(path string, listDir bool) http.FileSystem
- type AcceptSpec
- type AcceptSpecs
- type ContentType
- type FileOnlyFilesystem
- type GzipResponse
- func (g *GzipResponse) BytesWritten() int
- func (g *GzipResponse) Close() error
- func (g *GzipResponse) CloseNotify() <-chan bool
- func (g *GzipResponse) Flush()
- func (g *GzipResponse) Header() http.Header
- func (g *GzipResponse) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (g *GzipResponse) Push(target string, opts *http.PushOptions) error
- func (g *GzipResponse) Status() int
- func (g *GzipResponse) Unwrap() http.ResponseWriter
- func (g *GzipResponse) Write(b []byte) (int, error)
- func (g *GzipResponse) WriteHeader(code int)
- type Locale
- type Params
- func (p *Params) FormArrayValue(key string) []string
- func (p *Params) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (p *Params) FormValue(key string) string
- func (p *Params) PathValue(key string) string
- func (p *Params) QueryArrayValue(key string) []string
- func (p *Params) QueryValue(key string) string
- type Request
- type Response
- func (r *Response) BytesWritten() int
- func (r *Response) Close() error
- func (r *Response) CloseNotify() <-chan bool
- func (r *Response) Flush()
- func (r *Response) Header() http.Header
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) Push(target string, opts *http.PushOptions) error
- func (r *Response) Status() int
- func (r *Response) Unwrap() http.ResponseWriter
- func (r *Response) Write(b []byte) (int, error)
- func (r *Response) WriteHeader(code int)
- type ResponseWriter
Constants ¶
const ( MethodGet = "GET" MethodHead = "HEAD" MethodOptions = "OPTIONS" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodTrace = "TRACE" )
HTTP Method names
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderCacheControl = "Cache-Control" HeaderConnection = "Connection" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderCookie = "Cookie" HeaderHost = "Host" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLocation = "Location" HeaderLastModified = "Last-Modified" HeaderMethod = "Method" HeaderReferer = "Referer" HeaderServer = "Server" HeaderSetCookie = "Set-Cookie" HeaderStatus = "Status" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderOrigin = "Origin" HeaderTransferEncoding = "Transfer-Encoding" HeaderUpgrade = "Upgrade" HeaderUserAgent = "User-Agent" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXCSRFToken = "X-CSRF-Token" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedPort = "X-Forwarded-Port" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedServer = "X-Forwarded-Server" HeaderXFrameOptions = "X-Frame-Options" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-Ip" HeaderXRequestedWith = "X-Requested-With" HeaderXRequestID = "X-Request-Id" HeaderXXSSProtection = "X-XSS-Protection" )
HTTP Header names
const Version = "0.4.1"
Version no. of aah framework ahttp library
Variables ¶
var ( // ContentTypeHTML HTML content type. ContentTypeHTML = &ContentType{ Mime: "text/html", Exts: []string{".html", ".htm"}, Params: map[string]string{ "charset": "utf-8", }, } // ContentTypeJSON JSON content type. ContentTypeJSON = &ContentType{ Mime: "application/json", Exts: []string{".json"}, Params: map[string]string{ "charset": "utf-8", }, } // ContentTypeXML XML content type. ContentTypeXML = &ContentType{ Mime: "application/xml", Exts: []string{".xml"}, Params: map[string]string{ "charset": "utf-8", }, } // ContentTypeMultipartForm form data and File. ContentTypeMultipartForm = &ContentType{ Mime: "multipart/form-data", } // ContentTypeForm form data type. ContentTypeForm = &ContentType{ Mime: "application/x-www-form-urlencoded", } // ContentTypePlainText content type. ContentTypePlainText = &ContentType{ Mime: "text/plain", Params: map[string]string{ "charset": "utf-8", }, } // ContentTypeOctetStream content type for bytes. ContentTypeOctetStream = &ContentType{ Mime: "application/octet-stream", } )
var ErrDirListNotAllowed = errors.New("directory listing not allowed")
ErrDirListNotAllowed error is used for directory listing not allowed
Functions ¶
Types ¶
type AcceptSpec ¶
AcceptSpec used for HTTP Accept, Accept-Language, Accept-Encoding header value and it's quality. Implementation follows the specification of RFC7231 https://tools.ietf.org/html/rfc7231#section-5.3
func NegotiateEncoding ¶
func NegotiateEncoding(req *http.Request) *AcceptSpec
NegotiateEncoding negotiates the `Accept-Encoding` from the given HTTP request. Most quailfied one based on quality factor.
type AcceptSpecs ¶
type AcceptSpecs []AcceptSpec
AcceptSpecs is list of values parsed from header and sorted by quality factor.
func ParseAccept ¶
func ParseAccept(req *http.Request, hdrKey string) AcceptSpecs
ParseAccept parses the HTTP Accept* headers from `http.Request` returns the specification with quality factor as per RFC7231 https://tools.ietf.org/html/rfc7231#section-5.3. Level value is not honored.
Good read - http://stackoverflow.com/a/5331486/1343356 and http://stackoverflow.com/questions/13890996/http-accept-level
Known issues with WebKit and IE http://www.newmediacampaigns.com/blog/browser-rest-http-accept-headers
func ParseAcceptEncoding ¶
func ParseAcceptEncoding(req *http.Request) AcceptSpecs
ParseAcceptEncoding parses the HTTP `Accept-Encoding` header from `http.Request` as per RFC7231 https://tools.ietf.org/html/rfc7231#section-5.3.4. It returns `AcceptSpecs`.
func (AcceptSpecs) Less ¶
func (specs AcceptSpecs) Less(i, j int) bool
func (AcceptSpecs) MostQualified ¶
func (specs AcceptSpecs) MostQualified() *AcceptSpec
MostQualified returns the most quailfied accept spec, since `AcceptSpec` is sorted by quaity factor. First position is the most quailfied otherwise `nil`.
func (AcceptSpecs) Swap ¶
func (specs AcceptSpecs) Swap(i, j int)
type ContentType ¶
ContentType is represents request and response content type values
func NegotiateContentType ¶
func NegotiateContentType(req *http.Request) *ContentType
NegotiateContentType negotiates the response `Content-Type` from the given HTTP `Accept` header. The resolve order is- 1) URL extension 2) Accept header Most quailfied one based quality factor otherwise default is HTML.
func ParseContentType ¶
func ParseContentType(req *http.Request) *ContentType
ParseContentType resolves the request `Content-Type` from the given HTTP request via header `Content-Type`. Partial implementation of https://tools.ietf.org/html/rfc1521#section-4 i.e. parsing only type, subtype, parameters based on RFC.
func (*ContentType) Charset ¶
func (c *ContentType) Charset(defaultCharset string) string
Charset returns charset of content-type otherwise `defaultCharset` is returned
For e.g.: Content-Type: application/json; charset=utf-8 Method returns `utf-8`
func (*ContentType) IsEqual ¶
func (c *ContentType) IsEqual(contentType string) bool
IsEqual method compare give Content-Type string wth instance.
E.g.: contentType.IsEqual("application/json")
func (*ContentType) Raw ¶
func (c *ContentType) Raw() string
Raw method returns complete Content-Type composed.
E.g.: application/json; charset=utf-8; version=2
func (*ContentType) Version ¶
func (c *ContentType) Version() string
Version returns Accept header version paramater value if present otherwise empty string
For e.g.: Accept: application/json; version=2 Method returns `2`
type FileOnlyFilesystem ¶
type FileOnlyFilesystem struct { Fs http.FileSystem // contains filtered or unexported fields }
FileOnlyFilesystem extends/wraps `http.FileSystem` to disable directory listing functionality
type GzipResponse ¶
type GzipResponse struct {
// contains filtered or unexported fields
}
GzipResponse extends `ahttp.Response` and provides gzip for response bytes before writing them to the underlying response.
func (*GzipResponse) BytesWritten ¶
func (g *GzipResponse) BytesWritten() int
BytesWritten method returns no. of bytes already written into HTTP response.
func (*GzipResponse) Close ¶
func (g *GzipResponse) Close() error
Close method closes the writer if possible.
func (*GzipResponse) CloseNotify ¶
func (g *GzipResponse) CloseNotify() <-chan bool
CloseNotify method calls underlying CloseNotify method if it's compatible
func (*GzipResponse) Flush ¶
func (g *GzipResponse) Flush()
Flush method calls underlying Flush method if it's compatible
func (*GzipResponse) Header ¶
func (g *GzipResponse) Header() http.Header
Header method returns response header map.
func (*GzipResponse) Hijack ¶
func (g *GzipResponse) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack method calls underlying Hijack method if it's compatible otherwise returns an error. It becomes the caller's responsibility to manage and close the connection.
func (*GzipResponse) Push ¶
func (g *GzipResponse) Push(target string, opts *http.PushOptions) error
Push method calls underlying Push method HTTP/2 if compatible otherwise returns nil
func (*GzipResponse) Status ¶
func (g *GzipResponse) Status() int
Status method returns HTTP response status code. If status is not yet written it reurns 0.
func (*GzipResponse) Unwrap ¶
func (g *GzipResponse) Unwrap() http.ResponseWriter
Unwrap method returns the underlying `http.ResponseWriter`
func (*GzipResponse) Write ¶
func (g *GzipResponse) Write(b []byte) (int, error)
Write method writes bytes into Response.
func (*GzipResponse) WriteHeader ¶
func (g *GzipResponse) WriteHeader(code int)
WriteHeader method writes given status code into Response.
type Locale ¶
Locale value is negotiated from HTTP header `Accept-Language`
func NegotiateLocale ¶
NegotiateLocale negotiates the `Accept-Language` from the given HTTP request. Most quailfied one based on quality factor.
func ToLocale ¶
func ToLocale(a *AcceptSpec) *Locale
ToLocale creates a locale instance from `AcceptSpec`
type Params ¶
type Params struct { Path map[string]string Query url.Values Form url.Values File map[string][]*multipart.FileHeader }
Params structure holds value of Path, Query, Form and File.
func (*Params) FormArrayValue ¶
FormArrayValue methos returns value for given form key otherwise empty string.
func (*Params) FormFile ¶
FormFile method returns the first file for the provided form key otherwise returns error. It is caller responsibility to close the file.
func (*Params) FormValue ¶
FormValue methos returns value for given form key otherwise empty string.
func (*Params) PathValue ¶
PathValue method return value for given Path param key otherwise empty string.
func (*Params) QueryArrayValue ¶
QueryArrayValue method return array value for given query (aka URL) param key otherwise empty string.
func (*Params) QueryValue ¶
QueryValue method return value for given query (aka URL) param key otherwise empty string.
type Request ¶
type Request struct { // Schema value is protocol info it's a derived value in the order as below. // - `X-Forwarded-Proto` is not empty return value as is // - `http.Request.TLS` is not nil value is `https` // - `http.Request.TLS` is nil value is `http` Schema string // Host value of the HTTP 'Host' header (e.g. 'example.com:8080'). Host string // Method request method e.g. `GET`, `POST`, etc. Method string // Path the request URL Path e.g. `/booking/hotel.html`. Path string // Header request HTTP headers Header http.Header // Payload holds the value from HTTP request for `Content-Type` // JSON and XML. Payload []byte // ContentType the parsed HTTP header `Content-Type`. ContentType *ContentType // AcceptContentType negotiated value from HTTP Header `Accept`. // The resolve order is- // 1) URL extension // 2) Accept header. // Most quailfied one based on quality factor otherwise default is HTML. AcceptContentType *ContentType // AcceptEncoding negotiated value from HTTP Header the `Accept-Encoding` // Most quailfied one based on quality factor. AcceptEncoding *AcceptSpec // Params contains values from Path, Query, Form and File. Params *Params // Referer value of the HTTP 'Referrer' (or 'Referer') header. Referer string // UserAgent value of the HTTP 'User-Agent' header. UserAgent string // ClientIP remote client IP address. ClientIP string // Locale negotiated value from HTTP Header `Accept-Language`. Locale *Locale // IsJSONP is true if request query string has "callback=function_name". IsJSONP bool // IsGzipAccepted is true if the HTTP client accepts Gzip response. // otherwise false. IsGzipAccepted bool // Raw an object that Go HTTP server provied, Direct interaction with // raw object is not encouraged. Raw *http.Request }
Request is extends `http.Request` for aah framework
func ParseRequest ¶
ParseRequest method populates the given aah framework `ahttp.Request` instance from Go HTTP request.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response implements multiple interface (CloseNotifier, Flusher, Hijacker) and handy methods for aah framework.
func (*Response) BytesWritten ¶
BytesWritten method returns no. of bytes already written into HTTP response.
func (*Response) CloseNotify ¶
CloseNotify method calls underlying CloseNotify method if it's compatible
func (*Response) Flush ¶
func (r *Response) Flush()
Flush method calls underlying Flush method if it's compatible
func (*Response) Hijack ¶
Hijack method calls underlying Hijack method if it's compatible otherwise returns an error. It becomes the caller's responsibility to manage and close the connection.
func (*Response) Push ¶
func (r *Response) Push(target string, opts *http.PushOptions) error
Push method calls underlying Push method HTTP/2 if compatible otherwise returns nil
func (*Response) Status ¶
Status method returns HTTP response status code. If status is not yet written it reurns 0.
func (*Response) Unwrap ¶
func (r *Response) Unwrap() http.ResponseWriter
Unwrap method returns the underlying `http.ResponseWriter`
func (*Response) WriteHeader ¶
WriteHeader method writes given status code into Response.
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter // Status returns the HTTP status of the request otherwise 0 Status() int // BytesWritten returns the total number of bytes written BytesWritten() int // Unwrap returns the original `ResponseWriter` Unwrap() http.ResponseWriter }
ResponseWriter extends the `http.ResponseWriter` interface to implements aah framework response.
func WrapGzipResponseWriter ¶
func WrapGzipResponseWriter(w http.ResponseWriter, level int) ResponseWriter
WrapGzipResponseWriter wraps `http.ResponseWriter`, returns aah framework response writer that allows to advantage of response process.
func WrapResponseWriter ¶
func WrapResponseWriter(w http.ResponseWriter) ResponseWriter
WrapResponseWriter wraps `http.ResponseWriter`, returns aah framework response writer that allows to advantage of response process.