http

package
v0.0.0-...-9789875 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2021 License: MIT Imports: 12 Imported by: 0

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

View Source
const (
	ResponseStepStatusLine = iota
	ResponseStepHeader
	ResponseStepBody
)

Step flags for response stream processing.

View Source
const (
	MethodGet  = "GET"
	MethodPost = "POST"
)

RFC2616 Method

View Source
const (
	// HTTPVersion is unique http proto here.
	HTTPVersion = "HTTP/1.1"

	HeaderContentLength    = "Content-Length"
	HeaderHost             = "Host"
	HeaderContentTypeValue = "text/plain"
)

HTTP literal constants.

View Source
const (
	ServerRequestBufSize  = 256
	ServerResponseBufSize = 256
	ClientResponseBufSize = 256
	ClientRequestBufSize  = 256
	WriteBuffInitSize     = 256
)

Buffer size.

View Source
const (
	RequestStepRequestLine = iota
	RequestStepHeader
	RequestStepBody
)

Step flags for request strem processing.

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

RFC2616 Status Code

View Source
const DefaultMaxConnSizeForOne = 500

DefaultMaxConnSizeForOne is the default max size of active connections for one host.

Variables

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

func UnixSocketFile(host string) string

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 NewClient

func NewClient(network string) *Client

NewClient initilize a Client with DefaultMaxConnSizeForOne.

func NewClientSize

func NewClientSize(network string, maxConnSizeForOne int) *Client

NewClientSize initilize a Client with a specific maxConnSize.

func (*Client) Get

func (c *Client) Get(URL string) (resp *Response, err error)

Get implements GET Method of HTTP/1.1.

Must set the body and following headers in the request: * Content-Length * Host

func (*Client) Post

func (c *Client) Post(URL string, contentLength int64, body io.Reader) (resp *Response, err error)

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

func (c *Client) Send(req *Request) (resp *Response, err error)

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

type Handler interface {
	ServeHTTP(resp *Response, req *Request)
}

Handler processes the HTTP request and get the response.

Handler should not modify the request.

type HandlerFunc

type HandlerFunc func(resp *Response, req *Request)

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

func (resp *Response) Write(data []byte)

Write writes data to the response body and update the Content-Length header.

func (*Response) WriteStatus

func (resp *Response) WriteStatus(code int)

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.

func (*ResponseReader) Read

func (reader *ResponseReader) Read(p []byte) (n int, err error)

Read implements io.Reader interface.

type Server

type Server struct {
	Addr    string
	Network string
	// contains filtered or unexported fields
}

Server here resembles ServeMux in golang standard lib. Refer to https://golang.org/pkg/net/http/#ServeMux.

func NewServer

func NewServer(network string, host string) (s *Server)

NewServer initilizes the server of the speficif host. The host param includes the hostname and port.

func (*Server) AddHandler

func (srv *Server) AddHandler(pattern string, handler Handler)

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

func (srv *Server) Close() (err error)

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

func (srv *Server) ListenAndServe() (err error)

ListenAndServe starts listening and serve http connections. The method is blocking, which doesn't return until other goroutines close the server.

Jump to

Keyboard shortcuts

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