The Go Programming Language

Package http

import "http"

Package http implements parsing of HTTP requests, replies, and URLs and provides an extensible HTTP server and a basic HTTP client.

Package files

chunked.go client.go cookie.go dump.go fs.go header.go lex.go persist.go request.go response.go reverseproxy.go server.go sniff.go status.go transfer.go transport.go

Constants

HTTP status codes, defined in RFC 2616.

const (
    StatusContinue           = 100
    StatusSwitchingProtocols = 101

    StatusOK                   = 200
    StatusCreated              = 201
    StatusAccepted             = 202
    StatusNonAuthoritativeInfo = 203
    StatusNoContent            = 204
    StatusResetContent         = 205
    StatusPartialContent       = 206

    StatusMultipleChoices   = 300
    StatusMovedPermanently  = 301
    StatusFound             = 302
    StatusSeeOther          = 303
    StatusNotModified       = 304
    StatusUseProxy          = 305
    StatusTemporaryRedirect = 307

    StatusBadRequest                   = 400
    StatusUnauthorized                 = 401
    StatusPaymentRequired              = 402
    StatusForbidden                    = 403
    StatusNotFound                     = 404
    StatusMethodNotAllowed             = 405
    StatusNotAcceptable                = 406
    StatusProxyAuthRequired            = 407
    StatusRequestTimeout               = 408
    StatusConflict                     = 409
    StatusGone                         = 410
    StatusLengthRequired               = 411
    StatusPreconditionFailed           = 412
    StatusRequestEntityTooLarge        = 413
    StatusRequestURITooLong            = 414
    StatusUnsupportedMediaType         = 415
    StatusRequestedRangeNotSatisfiable = 416
    StatusExpectationFailed            = 417

    StatusInternalServerError     = 500
    StatusNotImplemented          = 501
    StatusBadGateway              = 502
    StatusServiceUnavailable      = 503
    StatusGatewayTimeout          = 504
    StatusHTTPVersionNotSupported = 505
)

DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting Server.MaxHeaderBytes.

const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

const DefaultMaxIdleConnsPerHost = 2

TimeFormat is the time format to use with time.Parse and time.Time.Format when parsing or generating times in HTTP headers. It is like time.RFC1123 but hard codes GMT as the time zone.

const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

Variables

var (
    ErrLineTooLong          = &ProtocolError{"header line too long"}
    ErrHeaderTooLong        = &ProtocolError{"header too long"}
    ErrShortBody            = &ProtocolError{"entity body too short"}
    ErrNotSupported         = &ProtocolError{"feature not supported"}
    ErrUnexpectedTrailer    = &ProtocolError{"trailer header without chunked transfer encoding"}
    ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
    ErrNotMultipart         = &ProtocolError{"request Content-Type isn't multipart/form-data"}
    ErrMissingBoundary      = &ProtocolError{"no multipart boundary param Content-Type"}
)

Errors introduced by the HTTP server.

var (
    ErrWriteAfterFlush = os.NewError("Conn.Write called after Flush")
    ErrBodyNotAllowed  = os.NewError("http: response status code does not allow body")
    ErrHijacked        = os.NewError("Conn has been hijacked")
    ErrContentLength   = os.NewError("Conn.Write wrote more than the declared Content-Length")
)
var (
    ErrPersistEOF = &ProtocolError{"persistent connection closed"}
    ErrPipeline   = &ProtocolError{"pipeline error"}
)

DefaultClient is the default Client and is used by Get, Head, and Post.

var DefaultClient = &Client{}

DefaultServeMux is the default ServeMux used by Serve.

var DefaultServeMux = NewServeMux()

ErrBodyReadAfterClose is returned when reading a Request Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

var ErrBodyReadAfterClose = os.NewError("http: invalid Read on closed request Body")

ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which have timed out.

var ErrHandlerTimeout = os.NewError("http: Handler timeout")

ErrMissingFile is returned by FormFile when the provided file field name is either not present in the request or not a file field.

var ErrMissingFile = os.NewError("http: no such file")
var ErrNoCookie = os.NewError("http: named cookied not present")

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding".

func DetectContentType

func DetectContentType(data []byte) string

DetectContentType returns the sniffed Content-Type string for the given data. This function always returns a valid MIME type.

func DumpRequest

func DumpRequest(req *Request, body bool) (dump []byte, err os.Error)

DumpRequest returns the wire representation of req, optionally including the request body, for debugging. DumpRequest is semantically a no-op, but in order to dump the body, it reads the body data into memory and changes req.Body to refer to the in-memory copy. The documentation for Request.Write details which fields of req are used.

func DumpResponse

func DumpResponse(resp *Response, body bool) (dump []byte, err os.Error)

DumpResponse is like DumpRequest but dumps a response.

func Error

func Error(w ResponseWriter, error string, code int)

Error replies to the request with the specified error message and HTTP code.

func Handle

func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) os.Error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically nil, in which case the DefaultServeMux is used.

A trivial example server is:

package main

import (
	"http"
	"io"
	"log"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "hello, world!\n")
}

func main() {
	http.HandleFunc("/hello", HelloServer)
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.String())
	}
}

func ListenAndServeTLS

func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) os.Error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate followed by the CA's certificate.

A trivial example server is:

import (
	"http"
	"log"
)

func handler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("This is an example server.\n"))
}

func main() {
	http.HandleFunc("/", handler)
	log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
	err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
	if err != nil {
		log.Fatal(err)
	}
}

One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.

func NewChunkedReader

func NewChunkedReader(r *bufio.Reader) io.Reader

NewChunkedReader returns a new reader that translates the data read from r out of HTTP "chunked" format before returning it. The reader returns os.EOF when the final 0-length chunk is read.

NewChunkedReader is not needed by normal applications. The http package automatically decodes chunking when reading response bodies.

func NewChunkedWriter

func NewChunkedWriter(w io.Writer) io.WriteCloser

NewChunkedWriter returns a new writer that translates writes into HTTP "chunked" format before writing them to w. Closing the returned writer sends the final 0-length chunk that marks the end of the stream.

NewChunkedWriter is not needed by normal applications. The http package adds chunking automatically if handlers don't set a Content-Length header. Using NewChunkedWriter inside a handler would result in double chunking or chunking with a Content-Length length, both of which are wrong.

func NotFound

func NotFound(w ResponseWriter, r *Request)

NotFound replies to the request with an HTTP 404 not found error.

func ParseHTTPVersion

func ParseHTTPVersion(vers string) (major, minor int, ok bool)

ParseHTTPVersion parses a HTTP version string. "HTTP/1.0" returns (1, 0, true).

func ProxyFromEnvironment

func ProxyFromEnvironment(req *Request) (*url.URL, os.Error)

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). Either URL or an error is returned.

func ProxyURL

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, os.Error)

ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.

func Redirect

func Redirect(w ResponseWriter, r *Request, urlStr string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func Serve

func Serve(l net.Listener, handler Handler) os.Error

Serve accepts incoming HTTP connections on the listener l, creating a new service thread for each. The service threads read requests and then call handler to reply to them. Handler is typically nil, in which case the DefaultServeMux is used.

func ServeFile

func ServeFile(w ResponseWriter, r *Request, name string)

ServeFile replies to the request with the contents of the named file or directory.

func SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

type Client

A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

Client is not yet very configurable.

type Client struct {
    Transport RoundTripper // if nil, DefaultTransport is used


    // If CheckRedirect is not nil, the client calls it before
    // following an HTTP redirect. The arguments req and via
    // are the upcoming request and the requests made already,
    // oldest first. If CheckRedirect returns an error, the client
    // returns that error instead of issue the Request req.
    //
    // If CheckRedirect is nil, the Client uses its default policy,
    // which is to stop after 10 consecutive requests.
    CheckRedirect func(req *Request, via []*Request) os.Error
}

func (*Client) Do

func (c *Client) Do(req *Request) (resp *Response, err os.Error)

Do sends an HTTP request and returns an HTTP response, following policy (e.g. redirects, cookies, auth) as configured on the client.

Callers should close resp.Body when done reading from it.

Generally Get, Post, or PostForm will be used instead of Do.

func (*Client) Get

func (c *Client) Get(url string) (r *Response, err os.Error)

Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the Client's CheckRedirect function.

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)

Caller should close r.Body when done reading from it.

func (*Client) Head

func (c *Client) Head(url string) (r *Response, err os.Error)

Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the Client's CheckRedirect function.

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)

func (*Client) Post

func (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error)

Post issues a POST to the specified URL.

Caller should close r.Body when done reading from it.

func (*Client) PostForm

func (c *Client) PostForm(url string, data url.Values) (r *Response, err os.Error)

PostForm issues a POST to the specified URL, with data's keys and values urlencoded as the request body.

Caller should close r.Body when done reading from it.

type ClientConn

A ClientConn sends request and receives headers over an underlying connection, while respecting the HTTP keepalive logic. ClientConn supports hijacking the connection calling Hijack to regain control of the underlying net.Conn and deal with it as desired.

ClientConn is low-level and should not be needed by most applications. See Client.

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

func NewClientConn

func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewClientConn returns a new ClientConn reading and writing c. If r is not nil, it is the buffer to use when reading c.

func NewProxyClientConn

func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn

NewProxyClientConn works like NewClientConn but writes Requests using Request's WriteProxy method.

func (*ClientConn) Close

func (cc *ClientConn) Close() os.Error

Close calls Hijack and then also closes the underlying connection

func (*ClientConn) Do

func (cc *ClientConn) Do(req *Request) (resp *Response, err os.Error)

Do is convenience method that writes a request and reads a response.

func (*ClientConn) Hijack

func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)

Hijack detaches the ClientConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before the user or Read have signaled the end of the keep-alive logic. The user should not call Hijack while Read or Write is in progress.

func (*ClientConn) Pending

func (cc *ClientConn) Pending() int

Pending returns the number of unanswered requests that have been sent on the connection.

func (*ClientConn) Read

func (cc *ClientConn) Read(req *Request) (*Response, os.Error)

Read reads the next response from the wire. A valid response might be returned together with an ErrPersistEOF, which means that the remote requested that this be the last request serviced. Read can be called concurrently with Write, but not with another Read.

func (*ClientConn) Write

func (cc *ClientConn) Write(req *Request) (err os.Error)

Write writes a request. An ErrPersistEOF error is returned if the connection has been closed in an HTTP keepalive sense. If req.Close equals true, the keepalive connection is logically closed after this request and the opposing server is informed. An ErrUnexpectedEOF indicates the remote closed the underlying TCP connection, which is usually considered as graceful close.

A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.

type Cookie struct {
    Name       string
    Value      string
    Path       string
    Domain     string
    Expires    time.Time
    RawExpires string

    // MaxAge=0 means no 'Max-Age' attribute specified. 
    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
    // MaxAge>0 means Max-Age attribute present and given in seconds
    MaxAge   int
    Secure   bool
    HttpOnly bool
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}

func (*Cookie) String

func (c *Cookie) String() string

String returns the serialization of the cookie for use in a Cookie header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set).

type Dir

A Dir implements http.FileSystem using the native file system restricted to a specific directory tree.

type Dir string

func (Dir) Open

func (d Dir) Open(name string) (File, os.Error)

type File

A File is returned by a FileSystem's Open method and can be served by the FileServer implementation.

type File interface {
    Close() os.Error
    Stat() (*os.FileInfo, os.Error)
    Readdir(count int) ([]os.FileInfo, os.Error)
    Read([]byte) (int, os.Error)
    Seek(offset int64, whence int) (int64, os.Error)
}

type FileSystem

A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash ('/', U+002F) characters, regardless of host operating system convention.

type FileSystem interface {
    Open(name string) (File, os.Error)
}

type Flusher

The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.

Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.

type Flusher interface {
    // Flush sends any buffered data to the client.
    Flush()
}

type Handler

Objects implementing the Handler interface can be registered to serve a particular path or subtree in the HTTP server.

ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished and that the HTTP server can move on to the next request on the connection.

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

func FileServer

func FileServer(root FileSystem) Handler

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

To use the operating system's file system implementation, use http.Dir:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

func NotFoundHandler

func NotFoundHandler() Handler

NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply.

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.

func StripPrefix

func StripPrefix(prefix string, h Handler) Handler

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

func TimeoutHandler

func TimeoutHandler(h Handler, ns int64, msg string) Handler

TimeoutHandler returns a Handler that runs h with the given time limit.

The new Handler calls h.ServeHTTP to handle each request, but if a call runs for more than ns nanoseconds, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout.

type HandlerFunc

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

type HandlerFunc func(ResponseWriter, *Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP calls f(w, r).

A Header represents the key-value pairs in an HTTP header.

type Header map[string][]string

func (Header) Add

func (h Header) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values associated with key.

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key.

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". Get is a convenience method. For more complex queries, access the map directly.

func (Header) Set

func (h Header) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

func (Header) Write

func (h Header) Write(w io.Writer) os.Error

Write writes a header in wire format.

func (Header) WriteSubset

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) os.Error

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written.

type Hijacker

The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler to take over the connection.

type Hijacker interface {
    // Hijack lets the caller take over the connection.
    // After a call to Hijack(), the HTTP server library
    // will not do anything else with the connection.
    // It becomes the caller's responsibility to manage
    // and close the connection.
    Hijack() (net.Conn, *bufio.ReadWriter, os.Error)
}

type ProtocolError

HTTP request parsing errors.

type ProtocolError struct {
    ErrorString string
}

func (*ProtocolError) String

func (err *ProtocolError) String() string

type Request

A Request represents a parsed HTTP request header.

type Request struct {
    Method string   // GET, POST, PUT, etc.
    RawURL string   // The raw URL given in the request.
    URL    *url.URL // Parsed URL.


    // The protocol version for incoming requests.
    // Outgoing requests always use HTTP/1.1.
    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0


    // A header maps request lines to their values.
    // If the header says
    //
    //	accept-encoding: gzip, deflate
    //	Accept-Language: en-us
    //	Connection: keep-alive
    //
    // then
    //
    //	Header = map[string][]string{
    //		"Accept-Encoding": {"gzip, deflate"},
    //		"Accept-Language": {"en-us"},
    //		"Connection": {"keep-alive"},
    //	}
    //
    // HTTP defines that header names are case-insensitive.
    // The request parser implements this by canonicalizing the
    // name, making the first character and any characters
    // following a hyphen uppercase and the rest lowercase.
    Header Header

    // The message body.
    Body io.ReadCloser

    // ContentLength records the length of the associated content.
    // The value -1 indicates that the length is unknown.
    // Values >= 0 indicate that the given number of bytes may be read from Body.
    ContentLength int64

    // TransferEncoding lists the transfer encodings from outermost to innermost.
    // An empty list denotes the "identity" encoding.
    TransferEncoding []string

    // Whether to close the connection after replying to this request.
    Close bool

    // The host on which the URL is sought.
    // Per RFC 2616, this is either the value of the Host: header
    // or the host name given in the URL itself.
    Host string

    // The parsed form. Only available after ParseForm is called.
    Form url.Values

    // The parsed multipart form, including file uploads.
    // Only available after ParseMultipartForm is called.
    MultipartForm *multipart.Form

    // Trailer maps trailer keys to values.  Like for Header, if the
    // response has multiple trailer lines with the same key, they will be
    // concatenated, delimited by commas.
    Trailer Header

    // RemoteAddr allows HTTP servers and other software to record
    // the network address that sent the request, usually for
    // logging. This field is not filled in by ReadRequest and
    // has no defined format. The HTTP server in this package
    // sets RemoteAddr to an "IP:port" address before invoking a
    // handler.
    RemoteAddr string

    // TLS allows HTTP servers and other software to record
    // information about the TLS connection on which the request
    // was received. This field is not filled in by ReadRequest.
    // The HTTP server in this package sets the field for
    // TLS-enabled connections before invoking a handler;
    // otherwise it leaves the field nil.
    TLS *tls.ConnectionState
}

func NewRequest

func NewRequest(method, urlStr string, body io.Reader) (*Request, os.Error)

NewRequest returns a new Request given a method, URL, and optional body.

func ReadRequest

func ReadRequest(b *bufio.Reader) (req *Request, err os.Error)

ReadRequest reads and parses a request from b.

func (*Request) AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon.

func (*Request) Cookie

func (r *Request) Cookie(name string) (*Cookie, os.Error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found.

func (*Request) Cookies

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

Cookies parses and returns the HTTP cookies sent with the request.

func (*Request) FormFile

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

FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.

func (*Request) FormValue

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

FormValue returns the first value for the named component of the query. FormValue calls ParseMultipartForm and ParseForm if necessary.

func (*Request) MultipartReader

func (r *Request) MultipartReader() (*multipart.Reader, os.Error)

MultipartReader returns a MIME multipart reader if this is a multipart/form-data POST request, else returns nil and an error. Use this function instead of ParseMultipartForm to process the request body as a stream.

func (*Request) ParseForm

func (r *Request) ParseForm() (err os.Error)

ParseForm parses the raw query. For POST requests, it also parses the request body as a form. ParseMultipartForm calls ParseForm automatically. It is idempotent.

func (*Request) ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemory int64) os.Error

ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls ParseForm if necessary. After one call to ParseMultipartForm, subsequent calls have no effect.

func (*Request) ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast returns whether the HTTP protocol used in the request is at least major.minor.

func (*Request) Referer

func (r *Request) Referer() string

Referer returns the referring URL, if sent in the request.

Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the Header map as Header["Referer"]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header["Referrer"].

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

func (*Request) Write

func (req *Request) Write(w io.Writer) os.Error

Write writes an HTTP/1.1 request -- header and body -- in wire format. This method consults the following fields of req:

Host
RawURL, if non-empty, or else URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body

If Body is present, Content-Length is <= 0 and TransferEncoding hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.

func (*Request) WriteProxy

func (req *Request) WriteProxy(w io.Writer) os.Error

WriteProxy is like Write but writes the request in the form expected by an HTTP proxy. It includes the scheme and host name in the URI instead of using a separate Host: header line. If req.RawURL is non-empty, WriteProxy uses it unchanged instead of URL but still omits the Host: header.

type Response

Response represents the response from an HTTP request.

type Response struct {
    Status     string // e.g. "200 OK"
    StatusCode int    // e.g. 200
    Proto      string // e.g. "HTTP/1.0"
    ProtoMajor int    // e.g. 1
    ProtoMinor int    // e.g. 0


    // Header maps header keys to values.  If the response had multiple
    // headers with the same key, they will be concatenated, with comma
    // delimiters.  (Section 4.2 of RFC 2616 requires that multiple headers
    // be semantically equivalent to a comma-delimited sequence.) Values
    // duplicated by other fields in this struct (e.g., ContentLength) are
    // omitted from Header.
    //
    // Keys in the map are canonicalized (see CanonicalHeaderKey).
    Header Header

    // Body represents the response body.
    Body io.ReadCloser

    // ContentLength records the length of the associated content.  The
    // value -1 indicates that the length is unknown.  Unless RequestMethod
    // is "HEAD", values >= 0 indicate that the given number of bytes may
    // be read from Body.
    ContentLength int64

    // Contains transfer encodings from outer-most to inner-most. Value is
    // nil, means that "identity" encoding is used.
    TransferEncoding []string

    // Close records whether the header directed that the connection be
    // closed after reading Body.  The value is advice for clients: neither
    // ReadResponse nor Response.Write ever closes a connection.
    Close bool

    // Trailer maps trailer keys to values, in the same
    // format as the header.
    Trailer Header

    // The Request that was sent to obtain this Response.
    // Request's Body is nil (having already been consumed).
    // This is only populated for Client requests.
    Request *Request
}

func Get

func Get(url string) (r *Response, err os.Error)

Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)

Caller should close r.Body when done reading from it.

Get is a convenience wrapper around DefaultClient.Get.

func Head(url string) (r *Response, err os.Error)

Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the Client's CheckRedirect function.

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)

Head is a wrapper around DefaultClient.Head

func Post

func Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error)

Post issues a POST to the specified URL.

Caller should close r.Body when done reading from it.

Post is a wrapper around DefaultClient.Post

func PostForm

func PostForm(url string, data url.Values) (r *Response, err os.Error)

PostForm issues a POST to the specified URL, with data's keys and values urlencoded as the request body.

Caller should close r.Body when done reading from it.

PostForm is a wrapper around DefaultClient.PostForm

func ReadResponse

func ReadResponse(r *bufio.Reader, req *Request) (resp *Response, err os.Error)

ReadResponse reads and returns an HTTP response from r. The req parameter specifies the Request that corresponds to this Response. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer.

func (*Response) Cookies

func (r *Response) Cookies() []*Cookie

Cookies parses and returns the cookies set in the Set-Cookie headers.

func (*Response) ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast returns whether the HTTP protocol used in the response is at least major.minor.

func (*Response) Write

func (resp *Response) Write(w io.Writer) os.Error

Writes the response (header, body and trailer) in wire format. This method consults the following fields of resp:

StatusCode
ProtoMajor
ProtoMinor
RequestMethod
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior

type ResponseWriter

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

type ResponseWriter interface {
    // Header returns the header map that will be sent by WriteHeader.
    // Changing the header after a call to WriteHeader (or Write) has
    // no effect.
    Header() Header

    // Write writes the data to the connection as part of an HTTP reply.
    // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
    // before writing the data.
    Write([]byte) (int, os.Error)

    // WriteHeader sends an HTTP response header with status code.
    // If WriteHeader is not called explicitly, the first call to Write
    // will trigger an implicit WriteHeader(http.StatusOK).
    // Thus explicit calls to WriteHeader are mainly used to
    // send error codes.
    WriteHeader(int)
}

type ReverseProxy

ReverseProxy is an HTTP Handler that takes an incoming request and sends it to another server, proxying the response back to the client.

type ReverseProxy struct {
    // Director must be a function which modifies
    // the request into a new request to be sent
    // using Transport. Its response is then copied
    // back to the original client unmodified.
    Director func(*Request)

    // The Transport used to perform proxy requests.
    // If nil, DefaultTransport is used.
    Transport RoundTripper

    // FlushInterval specifies the flush interval, in
    // nanoseconds, to flush to the client while
    // coping the response body.
    // If zero, no periodic flushing is done.
    FlushInterval int64
}

func NewSingleHostReverseProxy

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy returns a new ReverseProxy that rewrites URLs to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.

func (*ReverseProxy) ServeHTTP

func (p *ReverseProxy) ServeHTTP(rw ResponseWriter, req *Request)

type RoundTripper

RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.

A RoundTripper must be safe for concurrent use by multiple goroutines.

type RoundTripper interface {
    // RoundTrip executes a single HTTP transaction, returning
    // the Response for the request req.  RoundTrip should not
    // attempt to interpret the response.  In particular,
    // RoundTrip must return err == nil if it obtained a response,
    // regardless of the response's HTTP status code.  A non-nil
    // err should be reserved for failure to obtain a response.
    // Similarly, RoundTrip should not attempt to handle
    // higher-level protocol details such as redirects,
    // authentication, or cookies.
    //
    // RoundTrip may modify the request. The request Headers field is
    // guaranteed to be initialized.
    RoundTrip(req *Request) (resp *Response, err os.Error)
}

DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes a new network connection for each call to Do and uses HTTP proxies as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) environment variables.

var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment}

type ServeMux

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

Patterns named fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receiver requests for any other paths in the "/images/" subtree.

Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".

ServeMux also takes care of sanitizing the URL request path, redirecting any request containing . or .. elements to an equivalent .- and ..-free URL.

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

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern.

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern.

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

type Server

A Server defines parameters for running an HTTP server.

type Server struct {
    Addr           string  // TCP address to listen on, ":http" if empty
    Handler        Handler // handler to invoke, http.DefaultServeMux if nil
    ReadTimeout    int64   // the net.Conn.SetReadTimeout value for new connections
    WriteTimeout   int64   // the net.Conn.SetWriteTimeout value for new connections
    MaxHeaderBytes int     // maximum size of request headers, DefaultMaxHeaderBytes if 0
}

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() os.Error

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. If srv.Addr is blank, ":http" is used.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) os.Error

ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections.

Filenames containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate followed by the CA's certificate.

If srv.Addr is blank, ":https" is used.

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) os.Error

Serve accepts incoming connections on the Listener l, creating a new service thread for each. The service threads read requests and then call srv.Handler to reply to them.

type ServerConn

A ServerConn reads requests and sends responses over an underlying connection, until the HTTP keepalive logic commands an end. ServerConn also allows hijacking the underlying connection by calling Hijack to regain control over the connection. ServerConn supports pipe-lining, i.e. requests can be read out of sync (but in the same order) while the respective responses are sent.

ServerConn is low-level and should not be needed by most applications. See Server.

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

func NewServerConn

func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn

NewServerConn returns a new ServerConn reading and writing c. If r is not nil, it is the buffer to use when reading c.

func (*ServerConn) Close

func (sc *ServerConn) Close() os.Error

Close calls Hijack and then also closes the underlying connection

func (*ServerConn) Hijack

func (sc *ServerConn) Hijack() (c net.Conn, r *bufio.Reader)

Hijack detaches the ServerConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before Read has signaled the end of the keep-alive logic. The user should not call Hijack while Read or Write is in progress.

func (*ServerConn) Pending

func (sc *ServerConn) Pending() int

Pending returns the number of unanswered requests that have been received on the connection.

func (*ServerConn) Read

func (sc *ServerConn) Read() (req *Request, err os.Error)

Read returns the next request on the wire. An ErrPersistEOF is returned if it is gracefully determined that there are no more requests (e.g. after the first request on an HTTP/1.0 connection, or after a Connection:close on a HTTP/1.1 connection).

func (*ServerConn) Write

func (sc *ServerConn) Write(req *Request, resp *Response) os.Error

Write writes resp in response to req. To close the connection gracefully, set the Response.Close field to true. Write should be considered operational until it returns an error, regardless of any errors returned on the Read side.

type Transport

Transport is an implementation of RoundTripper that supports http, https, and http proxies (for either http or https with CONNECT). Transport can also cache connections for future re-use.

type Transport struct {

    // Proxy specifies a function to return a proxy for a given
    // Request. If the function returns a non-nil error, the
    // request is aborted with the provided error.
    // If Proxy is nil or returns a nil *URL, no proxy is used.
    Proxy func(*Request) (*url.URL, os.Error)

    // Dial specifies the dial function for creating TCP
    // connections.
    // If Dial is nil, net.Dial is used.
    Dial func(net, addr string) (c net.Conn, err os.Error)

    DisableKeepAlives  bool
    DisableCompression bool

    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
    // (keep-alive) to keep to keep per-host.  If zero,
    // DefaultMaxIdleConnsPerHost is used.
    MaxIdleConnsPerHost int
    // contains filtered or unexported fields
}

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (resp *Response, err os.Error)

RoundTrip implements the RoundTripper interface.

Need more packages? The Package Dashboard provides a list of goinstallable packages.

Subdirectories

Name   Synopsis
..
cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
fcgi Package fcgi implements the FastCGI protocol.
httptest Package httptest provides utilities for HTTP testing.
pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
spdy

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.