ahttp

package
Version: v0.12.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2020 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
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

View Source
const (
	SchemeHTTP  = "http"
	SchemeHTTPS = "https"
	SchemeFTP   = "ftp"
)

URI Protocol scheme names

View Source
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

View Source
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

View Source
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")
)
View Source
var (
	// GzipLevel holds value from app config.
	GzipLevel int
)

Functions

func ClientIP

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

func Host(r *http.Request) string

Host method is to correct Host value from HTTP request.

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

func Scheme(r *http.Request) string

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

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

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

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

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

func (specs AcceptSpecs) Len() int

sort.Interface methods for accept spec

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) String

func (c ContentType) String() string

String is stringer interface

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

type Locale struct {
	Raw      string
	Language string
	Region   string
}

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

func NegotiateLocale

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

func NewLocale(value string) *Locale

NewLocale method returns locale instance for given locale string.

func ToLocale

func ToLocale(a *AcceptSpec) *Locale

ToLocale method creates a locale instance from `AcceptSpec`

func (Locale) String

func (l Locale) String() string

String is stringer interface.

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

func AcquireRequest(r *http.Request) *Request

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

func ParseRequest

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

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

func (r *Request) ClientIP() string

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) Cookie

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

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

func (*Request) Cookies

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

Cookies method returns all the cookies from HTTP request.

func (*Request) FormArrayValue

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

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

func (*Request) FormFile

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

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

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

func (*Request) IsAJAX

func (r *Request) IsAJAX() bool

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

func (*Request) IsJSONP

func (r *Request) IsJSONP() bool

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

func (*Request) Locale

func (r *Request) Locale() *Locale

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

func (*Request) PathValue

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

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

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

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

func (*Request) Referer

func (r *Request) Referer() string

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

func (*Request) Reset

func (r *Request) Reset()

Reset method resets request instance for reuse.

func (*Request) SaveFile

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

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.

func (*Request) SetLocale

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

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

func (*Request) URL

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

URL method return underlying request URL instance.

func (*Request) Unwrap

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

func (r *Request) UserAgent() string

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

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

func (r *Response) BytesWritten() int

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

func (*Response) Close

func (r *Response) Close() error

Close method closes the writer if possible. TODO for removal

func (*Response) CloseNotify

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

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) Header

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

Header method returns response header map.

func (*Response) Hijack

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

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

func (r *Response) Status() int

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) Write

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

Write method writes bytes into Response.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

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.

type URLParam

type URLParam struct {
	Key   string
	Value string
}

URLParam struct holds single URL parameter value.

type URLParams

type URLParams []URLParam

URLParams type is slice of type URLParam.

func (URLParams) Get

func (u URLParams) Get(key string) string

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

func (URLParams) ToMap

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

ToMap method returns URL parameters in type map.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL