ahttp

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2017 License: MIT Imports: 16 Imported by: 0

README

ahttp - aah framework

Build Status codecov Go Report Card Version GoDoc License

v0.4.1 released and tagged on Apr 28, 2017

HTTP Library built to process, manipulate Request and Response (headers, body, gzip, etc).

ahttp developed for aah framework. However, it's an independent library, can be used separately with any Go language project. Feel free to use it.

Installation

Stable Version - Production Ready
# install the library
go get -u aahframework.org/ahttp.v0

Visit official website https://aahframework.org to learn more.

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     = "GET"
	MethodHead    = "HEAD"
	MethodOptions = "OPTIONS"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH"
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodTrace   = "TRACE"
)

HTTP Method names

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

View Source
const Version = "0.4.1"

Version no. of aah framework ahttp library

Variables

View Source
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",
	}
)
View Source
var ErrDirListNotAllowed = errors.New("directory listing not allowed")

ErrDirListNotAllowed error is used for directory listing not allowed

Functions

func Dir

func Dir(path string, listDir bool) http.FileSystem

Dir method returns a `http.Filesystem` that can be directly used by http.FileServer(). It works the same as `http.Dir()` also provides ability to disable directory listing with `http.FileServer`

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

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

func (c *ContentType) String() string

String is stringer interface

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

func (FileOnlyFilesystem) Open

func (fs FileOnlyFilesystem) Open(name string) (http.File, error)

Open method is compliance with `http.FileSystem` interface and disables directory listing

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

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 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 creates a locale instance from `AcceptSpec`

func (*Locale) String

func (l *Locale) String() string

String is stringer interface.

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

func (p *Params) FormArrayValue(key string) []string

FormArrayValue methos returns value for given form key otherwise empty string.

func (*Params) FormFile

func (p *Params) 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 (*Params) FormValue

func (p *Params) FormValue(key string) string

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

func (*Params) PathValue

func (p *Params) PathValue(key string) string

PathValue method return value for given Path param key otherwise empty string.

func (*Params) QueryArrayValue

func (p *Params) QueryArrayValue(key string) []string

QueryArrayValue method return array value for given query (aka URL) param key otherwise empty string.

func (*Params) QueryValue

func (p *Params) QueryValue(key string) string

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

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

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

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

func (r *Request) Reset()

Reset method resets request instance for reuse.

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.

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

Jump to

Keyboard shortcuts

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