Go Home Page
The Go Programming Language

Package http

import "http"

The http package 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 dump.go fs.go lex.go persist.go request.go response.go server.go status.go transfer.go url.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
)

Variables

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

DefaultServeMux is the default ServeMux used by Serve.

var DefaultServeMux = NewServeMux()
var ErrPersistEOF = &ProtocolError{"persistent connection closed"}

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the HTTP 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 CanonicalPath

func CanonicalPath(path string) string

CanonicalPath applies the algorithm specified in RFC 2396 to simplify the path, removing unnecessary . and .. elements.

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.

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(c *Conn, 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.

func HandleFunc

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

HandleFunc registers the handler function for the given pattern in the DefaultServeMux.

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(c *http.Conn, req *http.Request) {
	io.WriteString(c, "hello, world!\n")
}

func main() {
	http.HandleFunc("/hello", HelloServer)
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Exit("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.

A trivial example server is:

import (
	"http"
	"log"
)

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

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

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

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.

func NotFound

func NotFound(c *Conn, req *Request)

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

func ParseQuery

func ParseQuery(query string) (m map[string][]string, err os.Error)

func Redirect

func Redirect(c *Conn, url 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(c *Conn, r *Request, name string)

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

func URLEscape

func URLEscape(s string) string

URLEscape converts a string into URL-encoded form.

func URLUnescape

func URLUnescape(s string) (string, os.Error)

URLUnescape unescapes a URL-encoded string, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.

type ClientConn

A ClientConn sends request and receives headers over an underlying connection, while respecting the HTTP keepalive logic. ClientConn is not responsible for closing the underlying connection. One must call Close to regain control of that connection and deal with it as desired.

type ClientConn struct {
    // contains 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 (*ClientConn) Close

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

Close detaches the ClientConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Close may be called before the user or Read have signaled the end of the keep-alive logic. The user should not call Close 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() (resp *Response, err 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) 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. Write can be called concurrently with Read, but not with another Write.

type Conn

A Conn represents the server side of a single active HTTP connection.

type Conn struct {
    RemoteAddr string   // network address of remote side
    Req        *Request // current HTTP request
    // contains unexported fields
}

func (*Conn) Flush

func (c *Conn) Flush()

Flush sends any buffered data to the client.

func (*Conn) Hijack

func (c *Conn) Hijack() (rwc io.ReadWriteCloser, buf *bufio.ReadWriter, err os.Error)

Hijack lets the caller take over the connection. After a call to c.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.

func (*Conn) SetHeader

func (c *Conn) SetHeader(hdr, val string)

SetHeader sets a header line in the eventual reply. For example, SetHeader("Content-Type", "text/html; charset=utf-8") will result in the header line

Content-Type: text/html; charset=utf-8

being sent. UTF-8 encoded HTML is the default setting for Content-Type in this library, so users need not make that particular call. Calls to SetHeader after WriteHeader (or Write) are ignored.

func (*Conn) Write

func (c *Conn) Write(data []byte) (n int, err os.Error)

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.

func (*Conn) WriteHeader

func (c *Conn) WriteHeader(code int)

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.

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 Conn 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(*Conn, *Request)
}

func FileServer

func FileServer(root, prefix string) Handler

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root. It strips prefix from the incoming requests before looking up the file name in the file system.

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.

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(*Conn, *Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(c *Conn, req *Request)

ServeHTTP calls f(c, req).

type ProtocolError

HTTP request parsing errors.

type ProtocolError struct {
    os.ErrorString
}

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   // Parsed URL.
    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0


    // A header mapping 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 map[string]string

    // 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 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 structure field is that the compiler
    // can diagnose programs that use the alternate
    // (correct English) spelling req.Referrer but cannot
    // diagnose programs that use Header["Referrer"].
    Referer string

    // The User-Agent: header string, if sent in the request.
    UserAgent string

    // The parsed form. Only available after ParseForm is called.
    Form map[string][]string

    // 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 map[string]string
}

func ReadRequest

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

ReadRequest reads and parses a request from b.

func (*Request) FormValue

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

FormValue returns the first value for the named component of the query. FormValue calls 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.

func (*Request) ParseForm

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

ParseForm parses the request body as a form for POST requests, or the raw query for GET requests. It is idempotent.

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) 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")
UserAgent (defaults to defaultUserAgent)
Referer
Header
Body

If Body is present, Write forces "Transfer-Encoding: chunked" as a header and then closes Body when finished sending it.

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


    // RequestMethod records the method used in the HTTP request.
    // Header fields such as Content-Length have method-specific meaning.
    RequestMethod string // e.g. "HEAD", "CONNECT", "GET", etc.


    // 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 map[string]string

    // 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.  Like for Header, if the
    // response has multiple trailer lines with the same key, they will be
    // concatenated, delimited by commas.
    Trailer map[string]string
}

func Get

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

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

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

finalURL is the URL from which the response was fetched -- identical to the input URL unless redirects were followed.

Caller should close r.Body when done reading it.

func Head

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

Head issues a HEAD to the specified URL.

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

func ReadResponse

func ReadResponse(r *bufio.Reader, requestMethod string) (resp *Response, err os.Error)

ReadResponse reads and returns an HTTP response from r. The RequestMethod parameter specifies the method used in the corresponding request (e.g., "GET", "HEAD"). 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) AddHeader

func (r *Response) AddHeader(key, value string)

AddHeader adds a value under the given key. Keys are not case sensitive.

func (*Response) GetHeader

func (r *Response) GetHeader(key string) (value string)

GetHeader returns the value of the response header with the given key. If there were multiple headers with this key, their values are concatenated, with a comma delimiter. If there were no response headers with the given key, GetHeader returns an empty string. Keys are not case sensitive.

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 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 paths, like "/favicon.ico", or subtrees, like "/images/" (note the trailing slash). Patterns must begin with /. 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.

In the future, the pattern syntax may be relaxed to allow an optional host-name at the beginning of the pattern, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without 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 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(*Conn, *Request))

HandleFunc registers the handler function for the given pattern.

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(c *Conn, req *Request)

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

type ServerConn

A ServerConn reads requests and sends responses over an underlying connection, until the HTTP keepalive logic commands an end. ServerConn does not close the underlying connection. Instead, the user calls Close and regains 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.

type ServerConn struct {
    // contains 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() (c net.Conn, r *bufio.Reader)

Close detaches the ServerConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Close may be called before Read has signaled the end of the keep-alive logic. The user should not call Close 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). Read can be called concurrently with Write, but not with another Read.

func (*ServerConn) Write

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

Write writes a repsonse. 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. Write can be called concurrently with Read, but not with another Write.

type URL

A URL represents a parsed URL (technically, a URI reference). The general form represented is:

scheme://[userinfo@]host/path[?query][#fragment]

The Raw, RawPath, and RawQuery fields are in "wire format" (special characters must be hex-escaped if not meant to have special meaning). All other fields are logical values; '+' or '%' represent themselves.

Note, the reason for using wire format for the query is that it needs to be split into key/value pairs before decoding.

type URL struct {
    Raw       string // the original string
    Scheme    string // scheme
    Authority string // [userinfo@]host
    Userinfo  string // userinfo
    Host      string // host
    RawPath   string // /path[?query][#fragment]
    Path      string // /path
    RawQuery  string // query
    Fragment  string // fragment
}

func ParseURL

func ParseURL(rawurl string) (url *URL, err os.Error)

ParseURL parses rawurl into a URL structure. The string rawurl is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

func ParseURLReference

func ParseURLReference(rawurlref string) (url *URL, err os.Error)

ParseURLReference is like ParseURL but allows a trailing #fragment.

func (*URL) String

func (url *URL) String() string

String reassembles url into a valid URL string.

There are redundant fields stored in the URL structure: the String method consults Scheme, Path, Host, Userinfo, RawQuery, and Fragment, but not Raw, RawPath or Authority.

type URLError

URLError reports an error and the operation and URL that caused it.

type URLError struct {
    Op    string
    URL   string
    Error os.Error
}

func (*URLError) String

func (e *URLError) String() string

type URLEscapeError

type URLEscapeError string

func (URLEscapeError) String

func (e URLEscapeError) String() string

Other packages

main

Subdirectories

Name   Synopsis
..
pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.