Documentation ¶
Overview ¶
Package http provides server and client interfaces in http protocol.
The reliable transmission protocol could be TCP and unix domain socket, both of which support transmission of a reliable stream of bytes.
For TCP transmission, IP and port could be extracted from the URL. To extend unix domain socket as the stream channel, we provide a transformation from URL to unix domain socket file description.
Default unix domain directory is /var/tmp/. The unix file for a host is located in the unix domain directory. For example.
http://localhost:8080/add --> socket:/var/tmp/localhost:8080 path:/add
Features ¶
The library supports concurrent and keep-alive http requests. But it doesn't support chuck transfer encoding for large data transferring.
- Server always uses keep-alive http connections regardless of "Connection: keep-alive" header.
- Content-Length and Host headers are necessary in requests.
- Content-Length header is necessary in responses.
- Header value is single.
- Request-URI must be absolute path. Like: "/add", "/incr".
Index ¶
Constants ¶
const ( ResponseStepStatusLine = iota ResponseStepHeader ResponseStepBody )
Step flags for response stream processing.
const ( MethodGet = "GET" MethodPost = "POST" )
RFC2616 Method
const ( // HTTPVersion is unique http proto here. HTTPVersion = "HTTP/1.1" HeaderContentLength = "Content-Length" HeaderHost = "Host" HeaderContentTypeValue = "text/plain" )
HTTP literal constants.
const ( ServerRequestBufSize = 256 ServerResponseBufSize = 256 ClientResponseBufSize = 256 ClientRequestBufSize = 256 WriteBuffInitSize = 256 )
Buffer size.
const ( RequestStepRequestLine = iota RequestStepHeader RequestStepBody )
Step flags for request strem processing.
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 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 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 )
RFC2616 Status Code
const DefaultMaxConnSizeForOne = 500
DefaultMaxConnSizeForOne is the default max size of active connections for one host.
Variables ¶
var ErrServerClosed = errors.New("http: Server closed")
ErrServerClosed is returned by the Server's Serve, ListenAndServe, and ListenAndServeTLS methods after a call to Shutdown or Close.
Functions ¶
func UnixDir ¶
func UnixDir(dir string)
UnixDir sets the dir for unix domain sockets. The default value is "/var/tmp"
func UnixSocketFile ¶
UnixSocketFile gets the corresponding domain socket file from the host. In case that unix dir is "/var/tmp/", the relation is below.
"localhost:8080" --> "/var/tmp/localhost:8080"
Types ¶
type Client ¶
type Client struct { // tcp or unix Network string // contains filtered or unexported fields }
Client sends the http request and recevice response. Supports concurrency on multiple connections.
func NewClientSize ¶
NewClientSize initilize a Client with a specific maxConnSize.
func (*Client) Get ¶
Get implements GET Method of HTTP/1.1.
Must set the body and following headers in the request: * Content-Length * Host
func (*Client) Post ¶
Post implements POST Method of HTTP/1.1.
Must set the body and following headers in the request: * Content-Length * Host
Write the contentLength bytes data into the body of HTTP request. Discard the sequential data after the reading contentLength bytes from body(io.Reader).
func (*Client) Send ¶
Send http request and returns an HTTP response.
An error is returned if caused by client policy (such as invalid HTTP response), or failure to speak HTTP (such as a network connectivity problem).
Note that a non-2xx status code doesn't mean any above errors.
If the returned error is nil, the Response will contain a non-nil Body which is the caller's responsibility to close. If the Body is not closed, the Client may not be able to reuse a keep-alive connection to the same server.
type Handler ¶
Handler processes the HTTP request and get the response.
Handler should not modify the request.
type HandlerFunc ¶
HandlerFunc responds to an HTTP request. Behave the same as he Handler.
var NotFoundHandler HandlerFunc = func(resp *Response, req *Request) { resp.Write([]byte{}) resp.WriteStatus(StatusNotFound) }
NotFoundHandler gives 404 with the blank content.
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w *Response, r *Request)
ServeHTTP calls f(w, r).
type Request ¶
type Request struct { Method string URL *url.URL Proto string // Header is key-value pair for simplicity. Header map[string]string ContentLength int64 Body io.Reader }
Request is the Http Request. The format is below.
Request = Request-Line *(( general-header | request-header | entity-header ) CRLF) CRLF [message-body] Request-Line = Method SP Request-URI SP HTTP-Version CRLF Header = Key: Value CRLF
type Response ¶
type Response struct { Status string StatusCode int Proto string // Header is key-value pair for simplicity. Header map[string]string ContentLength int64 // Body represents the response body. // // The http Client and Transport guarantee that Body is always // non-nil, even on responses without a body or responses with // a zero-length body. It is the caller's responsibility to // close Body. It does not attempt to reuse TCP connections // unless the Body is closed. Body *ResponseReader // contains filtered or unexported fields }
Response is the Http Response. The format is below.
Response = Status-Line *(( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ] Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF Header = Key: Value CRLF
func (*Response) Write ¶
Write writes data to the response body and update the Content-Length header.
func (*Response) WriteStatus ¶
WriteStatus sets the status code of the response.
type ResponseReader ¶
type ResponseReader struct {
// contains filtered or unexported fields
}
ResponseReader is reader of the response body.
func (*ResponseReader) Close ¶
func (reader *ResponseReader) Close()
Close should be called to release the TCP connection. It is the caller's responsibility to close Body. It implements io.Closer interface.
type Server ¶
Server here resembles ServeMux in golang standard lib. Refer to https://golang.org/pkg/net/http/#ServeMux.
func NewServer ¶
NewServer initilizes the server of the speficif host. The host param includes the hostname and port.
func (*Server) AddHandler ¶
AddHandler adds handler to the list of handlers.
"" pattern or nil handler is forbidden.
func (*Server) AddHandlerFunc ¶
func (srv *Server) AddHandlerFunc(pattern string, handlerFunc HandlerFunc)
AddHandlerFunc adds handlerFunc to the list of handlers.
func (*Server) Close ¶
Close immediately closes active net.Listener and any active connections.
Close returns any error returned from closing the Server's underlying Listener.
func (*Server) ListenAndServe ¶
ListenAndServe starts listening and serve http connections. The method is blocking, which doesn't return until other goroutines close the server.