aahframe.work: aahframe.work/ahttp Index | Files

package ahttp

import "aahframe.work/ahttp"

Package ahttp is to cater HTTP helper methods for aah framework. Like parse HTTP headers, ResponseWriter, content type, etc.

Index

Package Files

ahttp.go content_type.go gzip_response.go header.go request.go response.go

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
)

func ClientIP Uses

func ClientIP(r *http.Request, hdrs ...string) string

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 Host Uses

func Host(r *http.Request) string

Host method is to correct Host value from HTTP request.

func ReleaseRequest Uses

func ReleaseRequest(r *Request)

ReleaseRequest method resets the instance value and puts back to pool.

func ReleaseResponseWriter Uses

func ReleaseResponseWriter(aw ResponseWriter)

ReleaseResponseWriter method puts response writer back to pool.

func Scheme Uses

func Scheme(r *http.Request) string

Scheme method is to identify value of protocol value. It's derived value, Go language doesn't provide directly.

- `X-Forwarded-Proto` is not empty, returns as-is

- `X-Forwarded-Protocol` is not empty, returns as-is

- `X-Forwarded-Ssl == on` returns `https`

- `http.Request.TLS` is not nil returns `https`

- `X-Url-Scheme` is not empty, returns as-is

- returns `http`

type AcceptSpec Uses

type AcceptSpec struct {
    Raw    string
    Value  string
    Q      float32
    Params map[string]string
}

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 Uses

func NegotiateEncoding(req *http.Request) *AcceptSpec

NegotiateEncoding negotiates the `Accept-Encoding` from the given HTTP request. Most quailfied one based on quality factor.

func (AcceptSpec) GetParam Uses

func (a AcceptSpec) GetParam(key string, defaultValue string) string

GetParam method returns the Accept* header param value otherwise returns default value.

For e.g.:
	Accept: application/json; version=2

	Method returns `2` for key `version`

type AcceptSpecs Uses

type AcceptSpecs []AcceptSpec

AcceptSpecs is list of values parsed from header and sorted by quality factor.

func ParseAccept Uses

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 Uses

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) Len Uses

func (specs AcceptSpecs) Len() int

sort.Interface methods for accept spec

func (AcceptSpecs) Less Uses

func (specs AcceptSpecs) Less(i, j int) bool

func (AcceptSpecs) MostQualified Uses

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 Uses

func (specs AcceptSpecs) Swap(i, j int)

type ContentType Uses

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 Uses

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 Uses

func ParseContentType(req *http.Request) *ContentType

ParseContentType method parses the request header `Content-Type` as per RFC1521.

func (*ContentType) Charset Uses

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 Uses

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 Uses

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 Uses

func (c *ContentType) Raw() string

Raw method returns complete Content-Type composed.

E.g.: application/json; charset=utf-8; version=2

func (ContentType) String Uses

func (c ContentType) String() string

String is stringer interface

func (*ContentType) Vendor Uses

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 Uses

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 Uses

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 Uses

func (g *GzipResponse) BytesWritten() int

BytesWritten method returns no. of bytes already written into HTTP response.

func (*GzipResponse) Close Uses

func (g *GzipResponse) Close() error

Close method closes the writer if possible.

func (*GzipResponse) CloseNotify Uses

func (g *GzipResponse) CloseNotify() <-chan bool

CloseNotify method calls underlying CloseNotify method if it's compatible

func (*GzipResponse) Flush Uses

func (g *GzipResponse) Flush()

Flush method calls underlying Flush method if it's compatible

func (*GzipResponse) Header Uses

func (g *GzipResponse) Header() http.Header

Header method returns response header map.

func (*GzipResponse) Hijack Uses

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 Uses

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 Uses

func (g *GzipResponse) Status() int

Status method returns HTTP response status code. If status is not yet written it reurns 0.

func (*GzipResponse) Unwrap Uses

func (g *GzipResponse) Unwrap() http.ResponseWriter

Unwrap method returns the underlying `http.ResponseWriter`

func (*GzipResponse) Write Uses

func (g *GzipResponse) Write(b []byte) (int, error)

Write method writes bytes into Response.

func (*GzipResponse) WriteHeader Uses

func (g *GzipResponse) WriteHeader(code int)

WriteHeader method writes given status code into Response.

type Locale Uses

type Locale struct {
    Raw      string
    Language string
    Region   string
}

Locale value is negotiated from HTTP header `Accept-Language`

func NegotiateLocale Uses

func NegotiateLocale(req *http.Request) *Locale

NegotiateLocale method negotiates the `Accept-Language` from the given HTTP request. Most quailfied one based on quality factor.

func NewLocale Uses

func NewLocale(value string) *Locale

NewLocale method returns locale instance for given locale string.

func ToLocale Uses

func ToLocale(a *AcceptSpec) *Locale

ToLocale method creates a locale instance from `AcceptSpec`

func (Locale) String Uses

func (l Locale) String() string

String is stringer interface.

type Request Uses

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 Uses

func AcquireRequest(r *http.Request) *Request

AcquireRequest method populates the given aah framework `ahttp.Request` instance from Go HTTP request.

func ParseRequest Uses

func ParseRequest(r *http.Request, req *Request) *Request

ParseRequest method populates the given aah framework `ahttp.Request` instance from Go HTTP request.

func (*Request) AcceptContentType Uses

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 Uses

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 Uses

func (r *Request) Body() io.ReadCloser

Body method returns the HTTP request body.

func (*Request) ClientIP Uses

func (r *Request) ClientIP() string

ClientIP method returns remote client IP address aka Remote IP.

Refer to method `ahttp.ClientIP`.

func (*Request) ContentType Uses

func (r *Request) ContentType() *ContentType

ContentType method returns the parsed value of HTTP header `Content-Type` per RFC1521.

func (*Request) Cookie Uses

func (r *Request) Cookie(name string) (*http.Cookie, error)

Cookie method returns a named cookie from HTTP request otherwise error.

func (*Request) Cookies Uses

func (r *Request) Cookies() []*http.Cookie

Cookies method returns all the cookies from HTTP request.

func (*Request) FormArrayValue Uses

func (r *Request) FormArrayValue(key string) []string

FormArrayValue method returns array value for given form key otherwise empty string slice.

func (*Request) FormFile Uses

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

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 Uses

func (r *Request) FormValue(key string) string

FormValue method returns value for given form key otherwise empty string.

func (*Request) IsAJAX Uses

func (r *Request) IsAJAX() bool

IsAJAX method returns true if request header `X-Requested-With` is `XMLHttpRequest` otherwise false.

func (*Request) IsJSONP Uses

func (r *Request) IsJSONP() bool

IsJSONP method returns true if request URL query string has "callback=function_name". otherwise false.

func (*Request) Locale Uses

func (r *Request) Locale() *Locale

Locale method returns negotiated value from HTTP Header `Accept-Language` per RFC7231.

func (*Request) PathValue Uses

func (r *Request) PathValue(key string) string

PathValue method returns value for given Path param key otherwise empty string. For eg.: /users/:userId => PathValue("userId")

func (*Request) QueryArrayValue Uses

func (r *Request) QueryArrayValue(key string) []string

QueryArrayValue method returns array value for given URL query param key otherwise empty string slice.

func (*Request) QueryValue Uses

func (r *Request) QueryValue(key string) string

QueryValue method returns value for given URL query param key otherwise empty string.

func (*Request) Referer Uses

func (r *Request) Referer() string

Referer method returns value of HTTP 'Referrer' (or 'Referer') header.

func (*Request) Reset Uses

func (r *Request) Reset()

Reset method resets request instance for reuse.

func (*Request) SaveFile Uses

func (r *Request) SaveFile(key, dstFile string) (int64, error)

SaveFile method saves an uploaded multipart file for given key from the HTTP request into given destination

func (*Request) SetAcceptContentType Uses

func (r *Request) SetAcceptContentType(contentType *ContentType) *Request

SetAcceptContentType method is used to set Accept ContentType instance.

func (*Request) SetAcceptEncoding Uses

func (r *Request) SetAcceptEncoding(encoding *AcceptSpec) *Request

SetAcceptEncoding method is used to accept encoding spec instance.

func (*Request) SetContentType Uses

func (r *Request) SetContentType(contType *ContentType) *Request

SetContentType method is used to set ContentType instance.

func (*Request) SetLocale Uses

func (r *Request) SetLocale(locale *Locale) *Request

SetLocale method is used to set locale instance in to aah request.

func (*Request) URL Uses

func (r *Request) URL() *url.URL

URL method return underlying request URL instance.

func (*Request) Unwrap Uses

func (r *Request) Unwrap() *http.Request

Unwrap method returns the underlying *http.Request instance of Go HTTP server, direct interaction with raw object is not encouraged. Use it appropriately.

func (*Request) UserAgent Uses

func (r *Request) UserAgent() string

UserAgent method returns value of HTTP 'User-Agent' header.

type Response Uses

type Response struct {
    // contains filtered or unexported fields
}

Response implements multiple interface (CloseNotifier, Flusher, Hijacker) and handy methods for aah framework.

func (*Response) BytesWritten Uses

func (r *Response) BytesWritten() int

BytesWritten method returns no. of bytes already written into HTTP response.

func (*Response) Close Uses

func (r *Response) Close() error

Close method closes the writer if possible. TODO for removal

func (*Response) CloseNotify Uses

func (r *Response) CloseNotify() <-chan bool

CloseNotify method calls underlying CloseNotify method if it's compatible

func (*Response) Flush Uses

func (r *Response) Flush()

Flush method calls underlying Flush method if it's compatible

func (*Response) Header Uses

func (r *Response) Header() http.Header

Header method returns response header map.

func (*Response) Hijack Uses

func (r *Response) 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 (*Response) Push Uses

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 Uses

func (r *Response) Reset()

Reset method resets the instance value for repurpose.

func (*Response) Status Uses

func (r *Response) Status() int

Status method returns HTTP response status code. If status is not yet written it reurns 0.

func (*Response) Unwrap Uses

func (r *Response) Unwrap() http.ResponseWriter

Unwrap method returns the underlying `http.ResponseWriter`

func (*Response) Write Uses

func (r *Response) Write(b []byte) (int, error)

Write method writes bytes into Response.

func (*Response) WriteHeader Uses

func (r *Response) WriteHeader(code int)

WriteHeader method writes given status code into Response.

type ResponseWriter Uses

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 Uses

func AcquireResponseWriter(w http.ResponseWriter) ResponseWriter

AcquireResponseWriter method wraps given writer and returns the aah response writer.

func WrapGzipWriter Uses

func WrapGzipWriter(w io.Writer) ResponseWriter

WrapGzipWriter wraps `ahttp.ResponseWriter` with Gzip writer.

type URLParam Uses

type URLParam struct {
    Key   string
    Value string
}

URLParam struct holds single URL parameter value.

type URLParams Uses

type URLParams []URLParam

URLParams type is slice of type URLParam.

func (URLParams) Get Uses

func (u URLParams) Get(key string) string

Get method returns the value for the given key otherwise empty string.

func (URLParams) ToMap Uses

func (u URLParams) ToMap() map[string]string

ToMap method returns URL parameters in type map.

Package ahttp imports 18 packages (graph) and is imported by 26 packages. Updated 2019-02-20. Refresh now. Tools for package owners.