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 ClientIP(r *http.Request, hdrs ...string) string
- func Host(r *http.Request) string
- func ReleaseRequest(r *Request)
- func ReleaseResponseWriter(aw ResponseWriter)
- func Scheme(r *http.Request) string
- type AcceptSpec
- type AcceptSpecs
- type ContentType
- func (c *ContentType) Charset(defaultCharset string) string
- func (c *ContentType) GetParam(key string) string
- func (c *ContentType) IsEqual(contentType string) bool
- func (c *ContentType) Raw() string
- func (c ContentType) String() string
- func (c *ContentType) Vendor() string
- func (c *ContentType) Version() string
- 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 Request
- func (r *Request) AcceptContentType() *ContentType
- func (r *Request) AcceptEncoding() *AcceptSpec
- func (r *Request) Body() io.ReadCloser
- func (r *Request) ClientIP() string
- func (r *Request) ContentType() *ContentType
- func (r *Request) Cookie(name string) (*http.Cookie, error)
- func (r *Request) Cookies() []*http.Cookie
- func (r *Request) FormArrayValue(key string) []string
- func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (r *Request) FormValue(key string) string
- func (r *Request) IsAJAX() bool
- func (r *Request) IsJSONP() bool
- func (r *Request) Locale() *Locale
- func (r *Request) PathValue(key string) string
- func (r *Request) QueryArrayValue(key string) []string
- func (r *Request) QueryValue(key string) string
- func (r *Request) Referer() string
- func (r *Request) Reset()
- func (r *Request) SaveFile(key, dstFile string) (int64, error)
- func (r *Request) SetAcceptContentType(contentType *ContentType) *Request
- func (r *Request) SetAcceptEncoding(encoding *AcceptSpec) *Request
- func (r *Request) SetContentType(contType *ContentType) *Request
- func (r *Request) SetLocale(locale *Locale) *Request
- func (r *Request) URL() *url.URL
- func (r *Request) Unwrap() *http.Request
- func (r *Request) UserAgent() string
- 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) Reset()
- 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
- type URLParam
- type URLParams
Constants ¶
const ( MethodGet = http.MethodGet MethodHead = http.MethodHead MethodOptions = http.MethodOptions MethodPost = http.MethodPost MethodPut = http.MethodPut MethodPatch = http.MethodPatch MethodDelete = http.MethodDelete MethodConnect = http.MethodConnect MethodTrace = http.MethodTrace )
HTTP Method names
const ( SchemeHTTP = "http" SchemeHTTPS = "https" SchemeFTP = "ftp" )
URI Protocol scheme names
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderAcceptRanges = "Accept-Ranges" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAge = "Age" 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" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCookie = "Cookie" HeaderDate = "Date" HeaderETag = "Etag" HeaderExpires = "Expires" HeaderHost = "Host" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfRange = "If-Range" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderKeepAlive = "Keep-Alive" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderOrigin = "Origin" HeaderMethod = "Method" HeaderPublicKeyPins = "Public-Key-Pins" HeaderRange = "Range" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderRetryAfter = "Retry-After" HeaderServer = "Server" HeaderSetCookie = "Set-Cookie" HeaderStatus = "Status" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderTransferEncoding = "Transfer-Encoding" HeaderUpgrade = "Upgrade" HeaderUserAgent = "User-Agent" HeaderVary = "Vary" HeaderWWWAuthenticate = "Www-Authenticate" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDNSPrefetchControl = "X-Dns-Prefetch-Control" HeaderXCSRFToken = "X-Csrf-Token" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedPort = "X-Forwarded-Port" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXForwardedServer = "X-Forwarded-Server" HeaderXFrameOptions = "X-Frame-Options" HeaderXHTTPMethodOverride = "X-Http-Method-Override" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderXRealIP = "X-Real-Ip" HeaderXRequestedWith = "X-Requested-With" HeaderXRequestID = "X-Request-Id" HeaderXXSSProtection = "X-Xss-Protection" )
HTTP Header names
const TimeFormat = http.TimeFormat
TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.
Variables ¶
var ( // ContentTypeHTML HTML content type. ContentTypeHTML = parseMediaType("text/html; charset=utf-8") // ContentTypeJSON JSON content type. ContentTypeJSON = parseMediaType("application/json; charset=utf-8") // ContentTypeJSONText JSON text content type. ContentTypeJSONText = parseMediaType("text/json; charset=utf-8") // ContentTypeXML XML content type. ContentTypeXML = parseMediaType("application/xml; charset=utf-8") // ContentTypeXMLText XML text content type. ContentTypeXMLText = parseMediaType("text/xml; charset=utf-8") // ContentTypeMultipartForm form data and File. ContentTypeMultipartForm = parseMediaType("multipart/form-data") // ContentTypeForm form data type. ContentTypeForm = parseMediaType("application/x-www-form-urlencoded") // ContentTypePlainText content type. ContentTypePlainText = parseMediaType("text/plain; charset=utf-8") // ContentTypeOctetStream content type for bytes. ContentTypeOctetStream = parseMediaType("application/octet-stream") // ContentTypeJavascript content type. ContentTypeJavascript = parseMediaType("application/javascript; charset=utf-8") // ContentTypeEventStream Server-Sent Events content type. ContentTypeEventStream = parseMediaType("text/event-stream") // ContentTypeCSSText content type for stylesheets/CSS. ContentTypeCSSText = parseMediaType("text/css; charset=utf-8") )
var ( // GzipLevel holds value from app config. GzipLevel int )
Functions ¶
func ClientIP ¶
ClientIP method returns remote Client IP address aka Remote IP.
It parses in the order of given headers otherwise it uses default default header set `X-Forwarded-For`, `X-Real-IP`, "X-Appengine-Remote-Addr" and finally `http.Request.RemoteAddr`.
func ReleaseRequest ¶
func ReleaseRequest(r *Request)
ReleaseRequest method resets the instance value and puts back to pool.
func ReleaseResponseWriter ¶
func ReleaseResponseWriter(aw ResponseWriter)
ReleaseResponseWriter method puts response writer back to pool.
func Scheme ¶
Scheme method is to identify value of protocol value. It's is derived one, Go language doesn't provide directly.
`X-Forwarded-Proto` is not empty, returns as-is
`X-Forwarded-Protocol` is not empty, returns as-is
`http.Request.TLS` is not nil or `X-Forwarded-Ssl == on` returns `https`
`X-Url-Scheme` is not empty, returns as-is
returns `http`
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 method parses the request HTTP header `Accept-Encoding` 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 method 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 ¶
type ContentType struct { Mime string Exts []string Params map[string]string // contains filtered or unexported fields }
ContentType is represents request and response content type values
func NegotiateContentType ¶
func NegotiateContentType(req *http.Request) *ContentType
NegotiateContentType method 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 method parses the request header `Content-Type` as per RFC1521.
func (*ContentType) Charset ¶
func (c *ContentType) Charset(defaultCharset string) string
Charset method 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) GetParam ¶
func (c *ContentType) GetParam(key string) string
GetParam method returns the media type paramater of Accept Content-Type header otherwise returns empty string value.
For e.g.: Accept: application/json; version=2 Method returns `2` for key `version`
func (*ContentType) IsEqual ¶
func (c *ContentType) IsEqual(contentType string) bool
IsEqual method returns true if its equals to current content-type instance otherwise false.
E.g.: contentType.IsEqual("application/json") contentType.IsEqual("application/json; charset=utf-8")
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) Vendor ¶
func (c *ContentType) Vendor() string
Vendor method returns Accept header vendor info if present otherwise empty string
For e.g.: Accept: application/vnd.mycompany.myapp.customer-v2+json Method returns `mycompany.myapp.customer`
func (*ContentType) Version ¶
func (c *ContentType) Version() string
Version method returns Accept header version paramater value if present otherwise empty string
For e.g.: Accept: application/json; version=2 Accept: application/vnd.mycompany.myapp.customer-v2+json Method returns `2`
type GzipResponse ¶
type GzipResponse struct {
// contains filtered or unexported fields
}
GzipResponse extends `ahttp.Response` to provides gzip compression for response bytes 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 method negotiates the `Accept-Language` from the given HTTP request. Most quailfied one based on quality factor.
func ToLocale ¶
func ToLocale(a *AcceptSpec) *Locale
ToLocale method creates a locale instance from `AcceptSpec`
type Request ¶
type Request struct { // Scheme value is protocol, refer to method `ahttp.Scheme`. Scheme string // Host value is HTTP 'Host' header (e.g. 'example.com:8080'). Host string // Proto value is current HTTP request protocol. (e.g. HTTP/1.1, HTTP/2.0) Proto string // Method value is HTTP verb from request e.g. `GET`, `POST`, etc. Method string // Path value is request relative URL Path e.g. `/app/login.html`. Path string // Header is request HTTP headers Header http.Header // URLParams value is URL path parameters. URLParams URLParams // IsGzipAccepted is true if the HTTP client accepts Gzip response, // otherwise false. IsGzipAccepted bool // contains filtered or unexported fields }
Request type extends `http.Request` and provides multiple helper methods per industry RFC guideline for aah framework.
func AcquireRequest ¶
AcquireRequest method populates the given aah framework `ahttp.Request` instance from Go HTTP request.
func ParseRequest ¶
ParseRequest method populates the given aah framework `ahttp.Request` instance from Go HTTP request.
func (*Request) AcceptContentType ¶
func (r *Request) AcceptContentType() *ContentType
AcceptContentType method returns negotiated value.
The resolve order is-
1) URL extension
2) Accept header (As per RFC7231 and vendor type as per RFC4288)
Most quailfied one based on quality factor otherwise default is Plain text.
func (*Request) AcceptEncoding ¶
func (r *Request) AcceptEncoding() *AcceptSpec
AcceptEncoding method returns negotiated value from HTTP Header the `Accept-Encoding` As per RFC7231.
Most quailfied one based on quality factor.
func (*Request) Body ¶
func (r *Request) Body() io.ReadCloser
Body method returns the HTTP request body.
func (*Request) ClientIP ¶
ClientIP method returns remote client IP address aka Remote IP.
Refer to method `ahttp.ClientIP`.
func (*Request) ContentType ¶
func (r *Request) ContentType() *ContentType
ContentType method returns the parsed value of HTTP header `Content-Type` per RFC1521.
func (*Request) FormArrayValue ¶
FormArrayValue method returns array value for given form key otherwise empty string slice.
func (*Request) FormFile ¶
FormFile method returns the first file for the provided form key otherwise returns error. It is caller responsibility to close the file.
func (*Request) FormValue ¶
FormValue method returns value for given form key otherwise empty string.
func (*Request) IsAJAX ¶
IsAJAX method returns true if request header `X-Requested-With` is `XMLHttpRequest` otherwise false.
func (*Request) IsJSONP ¶
IsJSONP method returns true if request URL query string has "callback=function_name". otherwise false.
func (*Request) Locale ¶
Locale method returns negotiated value from HTTP Header `Accept-Language` per RFC7231.
func (*Request) PathValue ¶
PathValue method returns value for given Path param key otherwise empty string. For eg.: /users/:userId => PathValue("userId")
func (*Request) QueryArrayValue ¶
QueryArrayValue method returns array value for given URL query param key otherwise empty string slice.
func (*Request) QueryValue ¶
QueryValue method returns value for given URL query param key otherwise empty string.
func (*Request) SaveFile ¶
SaveFile method saves an uploaded multipart file for given key from the HTTP request into given destination
func (*Request) SetAcceptContentType ¶
func (r *Request) SetAcceptContentType(contentType *ContentType) *Request
SetAcceptContentType method is used to set Accept ContentType instance.
func (*Request) SetAcceptEncoding ¶
func (r *Request) SetAcceptEncoding(encoding *AcceptSpec) *Request
SetAcceptEncoding method is used to accept encoding spec instance.
func (*Request) SetContentType ¶
func (r *Request) SetContentType(contType *ContentType) *Request
SetContentType method is used to set ContentType instance.
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) Reset ¶
func (r *Response) Reset()
Reset method resets the instance value for repurpose.
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 AcquireResponseWriter ¶
func AcquireResponseWriter(w http.ResponseWriter) ResponseWriter
AcquireResponseWriter method wraps given writer and returns the aah response writer.
func WrapGzipWriter ¶
func WrapGzipWriter(w io.Writer) ResponseWriter
WrapGzipWriter wraps `ahttp.ResponseWriter` with Gzip writer.