cnp-go: contnet.org/lib/cnp-go Index | Files

package cnp

import "contnet.org/lib/cnp-go"

Package cnp provides CNP client and server implementations.

Index

Package Files

client.go cnp.go common.go error.go header.go message.go request.go response.go server.go

Constants

const (
    // DefaultPort represents the default port for the cnp:// schema.
    DefaultPort = 25454

    // MaxHeaderLength is the maximum byte size of the header.
    MaxHeaderLength = 1 * 1024 * 1024

    // VersionMajor is the major CNP version (X in cnp/X.Y).
    VersionMajor = 0

    // VersionMinor is the minor CNP version (Y in cnp/X.Y).
    VersionMinor = 4
)
const (
    // ReasonSyntax represents the "syntax" reason parameter value.
    ReasonSyntax = "syntax"
    // ReasonVersion represents the "version" reason parameter value.
    ReasonVersion = "version"
    // ReasonInvalid represents the "invalid" reason parameter value.
    ReasonInvalid = "invalid"
    // ReasonNotSupported represents the "not_supported" reason parameter value.
    ReasonNotSupported = "not_supported"
    // ReasonTooLarge represents the "too_large" reason parameter value.
    ReasonTooLarge = "too_large"
    // ReasonNotFound represents the "not_found" reason parameter value.
    ReasonNotFound = "not_found"
    // ReasonDenied represents the "denied" reason parameter value.
    ReasonDenied = "denied"
    // ReasonRejected represents the "rejected" reason parameter value.
    ReasonRejected = "rejected"
    // ReasonServerError represents the "server_error" reason parameter value.
    ReasonServerError = "server_error"
)
const (
    // IntentOK represents the "ok" response intent.
    IntentOK = "ok"
    // IntentNotModified represents the "not_modified" response intent.
    IntentNotModified = "not_modified"
    // IntentError represents the "error" response intent.
    IntentError = "error"
    // IntentRedirect represents the "redirect" response intent.
    IntentRedirect = "redirect"
)

func Clean Uses

func Clean(s string) string

Clean cleans a CNP request intent path.

This works the same as path.Clean(), but preserves a trailing slash.

func Escape Uses

func Escape(s string) []byte

Escape CNP-escapes the bytestring s.

func ListenAndServe Uses

func ListenAndServe(addr string, handler Handler) error

ListenAndServe creates a new Server with a listen address and a handler and calls its ListenAndServe method.

func Unescape Uses

func Unescape(data []byte) (string, error)

Unescape unescapes data from wire format into a bytestring.

type Error Uses

type Error interface {
    // CNPError returns the value of the "error" parameter in a CNP error
    // response.
    CNPError() string

    Error() string
}

Error represents an error as used in a CNP error response.

func NewError Uses

func NewError(reason string) Error

NewError returns a new Error based on a reason parameter value.

If the reason is blank, nil is returned. If the reason is unknown, ErrorServerError is returned.

type ErrorDenied Uses

type ErrorDenied struct {
    Reason string
}

ErrorDenied represents the CNP "denied" error reason.

func (ErrorDenied) CNPError Uses

func (e ErrorDenied) CNPError() string

CNPError on ErrorDenied returns the error parameter value "denied".

func (ErrorDenied) Error Uses

func (e ErrorDenied) Error() string

type ErrorInvalid Uses

type ErrorInvalid struct {
    Reason string
}

ErrorInvalid represents the CNP "invalid" error reason.

func (ErrorInvalid) CNPError Uses

func (e ErrorInvalid) CNPError() string

CNPError on ErrorInvalid returns the error parameter value "invalid".

func (ErrorInvalid) Error Uses

func (e ErrorInvalid) Error() string

type ErrorNotFound Uses

type ErrorNotFound struct {
    Reason string
}

ErrorNotFound represents the CNP "not_found" error reason.

func (ErrorNotFound) CNPError Uses

func (e ErrorNotFound) CNPError() string

CNPError on ErrorNotFound returns the error parameter value "not_found".

func (ErrorNotFound) Error Uses

func (e ErrorNotFound) Error() string

type ErrorNotSupported Uses

type ErrorNotSupported struct {
    Reason string
}

ErrorNotSupported represents the CNP "not_supported" error reason.

func (ErrorNotSupported) CNPError Uses

func (e ErrorNotSupported) CNPError() string

CNPError on ErrorNotSupported returns the error parameter value "not_supported".

func (ErrorNotSupported) Error Uses

func (e ErrorNotSupported) Error() string

type ErrorRejected Uses

type ErrorRejected struct {
    Reason string
}

ErrorRejected represents the CNP "rejected" error reason.

func (ErrorRejected) CNPError Uses

func (e ErrorRejected) CNPError() string

CNPError on ErrorRejected returns the error parameter value "rejected".

func (ErrorRejected) Error Uses

func (e ErrorRejected) Error() string

type ErrorServerError Uses

type ErrorServerError struct {
    Reason string
}

ErrorServerError represents the CNP "server_error" error reason.

func (ErrorServerError) CNPError Uses

func (e ErrorServerError) CNPError() string

CNPError on ErrorServerError returns the error parameter value "server_error".

func (ErrorServerError) Error Uses

func (e ErrorServerError) Error() string

type ErrorSyntax Uses

type ErrorSyntax struct {
    Reason string
}

ErrorSyntax represents the CNP "syntax" error reason.

func (ErrorSyntax) CNPError Uses

func (e ErrorSyntax) CNPError() string

CNPError on ErrorSyntax returns the error parameter value "syntax".

func (ErrorSyntax) Error Uses

func (e ErrorSyntax) Error() string

type ErrorTooLarge Uses

type ErrorTooLarge struct {
    Reason string
}

ErrorTooLarge represents the CNP "too_large" error reason.

func (ErrorTooLarge) CNPError Uses

func (e ErrorTooLarge) CNPError() string

CNPError on ErrorTooLarge returns the error parameter value "too_large".

func (ErrorTooLarge) Error Uses

func (e ErrorTooLarge) Error() string

type ErrorURL Uses

type ErrorURL struct {
    // Err represents the error reason.
    Err error
    // URL is the URL that triggered the error.
    URL string
}

ErrorURL is a non-CNPError that represents an invalid CNP URL.

func (ErrorURL) Error Uses

func (e ErrorURL) Error() string

type ErrorVersion Uses

type ErrorVersion struct {
    Reason string
}

ErrorVersion represents the CNP "version" error reason.

func (ErrorVersion) CNPError Uses

func (e ErrorVersion) CNPError() string

CNPError on ErrorVersion returns the error parameter value "version".

func (ErrorVersion) Error Uses

func (e ErrorVersion) Error() string

type Handler Uses

type Handler interface {
    // ServeCNP responds to a CNP request.
    //
    // This function must be safe for concurrent use.
    ServeCNP(resp ResponseWriter, req *Request)
}

Handler handles CNP requests accepted by the server.

type HandlerFunc Uses

type HandlerFunc func(resp ResponseWriter, req *Request)

HandlerFunc allows using raw functions as handlers.

func (HandlerFunc) ServeCNP Uses

func (h HandlerFunc) ServeCNP(resp ResponseWriter, req *Request)

ServeCNP calls h(resp, req).

type Header struct {
    // VersionMajor is the major CNP version given in the header.
    VersionMajor int
    // VersionMinor is the minor CNP version given in the header.
    VersionMinor int
    // Intent is the intent string of the message.
    Intent string
    // Parameters is a decoded map of the message parameters.
    Parameters Parameters
}

Header represents a CNP message header

func NewHeader Uses

func NewHeader(intent string, params Parameters) Header

NewHeader creates a new CNP header from an intent and optional parameter map.

func ParseHeader Uses

func ParseHeader(line []byte) (h Header, err error)

ParseHeader parses a CNP header from a bytestring. The line parameter must be a single line that ends with a line feed.

func (Header) String Uses

func (h Header) String() string

func (Header) Version Uses

func (h Header) Version() string

Version returns the message's CNP version as a "cnp/X.Y" string.

func (Header) Write Uses

func (h Header) Write(w io.Writer) (err error)

Write writes the CNP message header line in the wire format. The written line ends with a line feed.

type Message Uses

type Message struct {
    Header Header
    Body   io.Reader
    // contains filtered or unexported fields
}

Message represents a CNP message.

func NewMessage Uses

func NewMessage(intent string, body io.Reader) *Message

NewMessage creates a new CNP message.

This method also calls Message.TryComputeLength().

func ParseMessage Uses

func ParseMessage(r io.Reader) (*Message, error)

ParseMessage parses a CNP message.

The message's Body field is set to a bufio.Reader wrapping r. If r is an io.Closer, it is also stored separately for usage with Message.Close().

func (*Message) Close Uses

func (msg *Message) Close() error

Close attempts to close the message body reader.

If the message's Body field is an io.Closer, its Close() method is called. If Body is not an io.Closer and the message was created with ParseMessage provided with an io.Closer, the Close() method on the original reader will be called. Otherwise, this function does nothing.

func (*Message) ComputeLength Uses

func (msg *Message) ComputeLength() error

ComputeLength sets the length header parameter based on the message body. First, msg.TryComputeLength() is attempted; if that fails, the request is fully read into a bytes.Buffer and msg.Body is set to it.

func (*Message) Intent Uses

func (msg *Message) Intent() string

Intent retrieves the message header intent.

func (*Message) Length Uses

func (msg *Message) Length() int64

Length gets the length header parameter (or 0 if it's not set or invalid).

func (*Message) Param Uses

func (msg *Message) Param(key string) string

Param retrieves a header parameter. It performs no value validation.

func (*Message) SetIntent Uses

func (msg *Message) SetIntent(s string)

SetIntent sets the message header intent.

func (*Message) SetLength Uses

func (msg *Message) SetLength(n int64)

SetLength sets the length header parameter to n.

If negative or zero, the parameter is unset.

func (*Message) SetParam Uses

func (msg *Message) SetParam(key, value string)

SetParam sets a header parameter. If the value is empty, the parameter is unset. It performs no value validation.

func (*Message) TryComputeLength Uses

func (msg *Message) TryComputeLength() bool

TryComputeLength sets the length header parameter to the length of the message body if the body's type is one of *bytes.Buffer, *bytes.Reader or *strings.Reader and returns true. If msg.Body is nil, the length parameter is unset and the function returns true. Otherwise, false is returned and the length parameter remains unchanged.

func (*Message) Validate Uses

func (msg *Message) Validate() error

Validate validates the message header parameter value format (length).

func (*Message) Write Uses

func (msg *Message) Write(w io.Writer) error

Write writes the message header and body to w.

type Parameters Uses

type Parameters map[string]string

Parameters represents CNP message parameter key=value pairs.

func (Parameters) Write Uses

func (p Parameters) Write(w io.Writer) (err error)

Write writes the parameters encoded for inclusion in the wire format. Includes a leading space if p is nonempty.

type Request Uses

type Request struct {
    Message
}

Request represents a CNP request message.

func NewRequest Uses

func NewRequest(host, pth string, body []byte) (*Request, error)

NewRequest creates a new Request from a host, path and optional body data.

func NewRequestURL Uses

func NewRequestURL(urlStr string, body []byte) (*Request, error)

NewRequestURL creates a new Request from a URL and optional body data.

func ParseRequest Uses

func ParseRequest(r io.Reader) (*Request, error)

ParseRequest parses a request message.

func (*Request) Host Uses

func (r *Request) Host() string

Host returns the host part of the request intent.

func (*Request) HostPath Uses

func (r *Request) HostPath() (host string, pth string)

HostPath returns the host and path parts of the request intent.

func (*Request) IfModified Uses

func (r *Request) IfModified() time.Time

IfModified retrieves the if_modified request parameter.

If the parameter isn't a valid RFC3339 timestamp, a zero time.Time is returned.

func (*Request) Length Uses

func (r *Request) Length() int64

Length gets the length request parameter (or 0 if not set or invalid).

func (*Request) Name Uses

func (r *Request) Name() string

Name retrieves the name request parameter.

If the name request parameter is not a valid filename, an empty string is returned.

func (*Request) Path Uses

func (r *Request) Path() string

Path returns the path part of the request intent.

func (*Request) Select Uses

func (r *Request) Select() (selector, query string)

Select retrieves the select request parameter.

If the parameter isn't a valid selector, empty strings are returned.

func (*Request) SetHost Uses

func (r *Request) SetHost(host string) error

SetHost sets the host part of the request intent, leaving path unchanged.

func (*Request) SetHostPath Uses

func (r *Request) SetHostPath(host, pth string) error

SetHostPath sets the request intent.

func (*Request) SetIfModified Uses

func (r *Request) SetIfModified(t time.Time)

SetIfModified sets the if_modified request parameter.

If t is the zero time value, the if_modified parameter is unset.

func (*Request) SetLength Uses

func (r *Request) SetLength(n int64)

SetLength sets the length request parameter to n.

If n is negative or zero, the parameter is unset.

func (*Request) SetName Uses

func (r *Request) SetName(name string) error

SetName sets the name request parameter.

Returns an error if the name includes characters not valid in a filename (slash, null byte).

func (*Request) SetPath Uses

func (r *Request) SetPath(pth string) error

SetPath sets the path part of the request intent, leaving host unchanged.

func (*Request) SetSelect Uses

func (r *Request) SetSelect(selector, query string) error

SetSelect sets the select request parameter.

If the selector name is empty, the select parameter is unset.

func (*Request) SetType Uses

func (r *Request) SetType(typ string) error

SetType sets the type request parameter.

Returns an error if typ is not a valid format for a MIME type.

func (*Request) Type Uses

func (r *Request) Type() string

Type retrieves the type request parameter.

If the type request parameter is invalid or empty, the default value "application/octet-stream" is returned.

func (*Request) URL Uses

func (r *Request) URL() *url.URL

URL returns a cnp:// URL based on this request's intent.

func (*Request) Validate Uses

func (r *Request) Validate() error

Validate validates the request header intent and parameter value format (length, name, type, if_modified, select)

func (*Request) Write Uses

func (r *Request) Write(w io.Writer) error

Write ensures that the request's length parameter is set if it has body and then writes it to w.

type Response Uses

type Response struct {
    Message
}

Response represents a CNP response message.

func Get Uses

func Get(url string) (*Response, error)

Get sends a body-less request to a given URL.

func NewResponse Uses

func NewResponse(intent string, body []byte) (resp *Response, err error)

NewResponse creates a new Response from a response intent and optional body data.

func ParseResponse Uses

func ParseResponse(r io.Reader) (*Response, error)

ParseResponse parses a response message.

func Send Uses

func Send(r *Request) (*Response, error)

Send sends a CNP request to a server and returns the response.

The TCP connection is made using net.Dial.

func (*Response) Length Uses

func (r *Response) Length() int64

Length gets the length response parameter (or -1 if it's not set or invalid).

func (*Response) Location Uses

func (r *Response) Location() (host, path string, err error)

Location retrieves the host and path from the location response parameter.

If the location parameter is empty, it returns empty host and path. If the location parameter is invalid, an error is returned.

func (*Response) Modified Uses

func (r *Response) Modified() time.Time

Modified retrieves the modified Response parameter.

If the parameter isn't a valid RFC3339 timestamp, a zero time.Time is returned.

func (*Response) Name Uses

func (r *Response) Name() string

Name retrieves the name response parameter.

If the name response parameter is not a valid filename, an empty string is returned.

func (*Response) Reason Uses

func (r *Response) Reason() string

Reason retrieves the reason response parameter.

If the reason is nonempty and unknown, "server_error" is returned.

func (*Response) ResponseIntent Uses

func (r *Response) ResponseIntent() string

ResponseIntent retrieves the response intent. If the intent is unknown, the "error" intent is returned.

func (*Response) Select Uses

func (r *Response) Select() (selector, query string)

Select retrieves the select response parameter.

If the parameter isn't a valid selector, empty strings are returned.

func (*Response) SetLength Uses

func (r *Response) SetLength(n int64)

SetLength sets the length response parameter to n.

If negative, the parameter is unset.

func (*Response) SetLocation Uses

func (r *Response) SetLocation(host, path string) error

SetLocation sets the location response parameter to host and path.

Returns an error if the host or path are invalid.

func (*Response) SetModified Uses

func (r *Response) SetModified(t time.Time)

SetModified sets the modified response parameter.

If t is the zero time value, the modified parameter is unset. Otherwise, if the time response parameter is empty, it's set to the current time.

func (*Response) SetName Uses

func (r *Response) SetName(name string) error

SetName sets the name response parameter.

Returns an error if the name includes characters not valid in a filename (slash, null byte).

func (*Response) SetReason Uses

func (r *Response) SetReason(reason string) error

SetReason sets the reason response parameter.

If the reason is nonempty and unknown, it sets "server_error" instead.

func (*Response) SetResponseIntent Uses

func (r *Response) SetResponseIntent(intent string) error

SetResponseIntent sets the response intent. If the provided intent is not a known response intent, an error is returned and the intent is set to "error".

func (*Response) SetSelect Uses

func (r *Response) SetSelect(selector, query string) error

SetSelect sets the select response parameter.

If the selector name is empty, the select parameter is unset.

func (*Response) SetTime Uses

func (r *Response) SetTime(t time.Time)

SetTime sets the time response parameter.

If t is the zero time value, the time parameter is unset.

func (*Response) SetType Uses

func (r *Response) SetType(typ string) error

SetType sets the type response parameter.

Returns an error if typ is not a valid format for a MIME type.

func (*Response) Time Uses

func (r *Response) Time() time.Time

Time retrieves the time response parameter.

If the parameter isn't a valid RFC3339 timestamp, a zero time.Time is returned.

func (*Response) Type Uses

func (r *Response) Type() string

Type retrieves the type response parameter.

If the type response parameter is invalid or empty, the default value "application/octet-stream" is returned.

func (*Response) Validate Uses

func (r *Response) Validate() error

Validate validates the response intent and header parameter value format (length, name, type, time, modified, location, reason, select)

func (*Response) Write Uses

func (r *Response) Write(w io.Writer) error

Write writes the response to w.

type ResponseWriter Uses

type ResponseWriter interface {
    // Response returns a Response object whose header will be written to the
    // socket. The body is nil and should be ignored.
    Response() *Response

    // RemoteAddr returns the network address of the client.
    RemoteAddr() net.Addr

    // WriteHeader sends a CNP header with an intent.
    WriteHeader() error

    // Write sends data in the CNP response body.
    //
    // If WriteHeader has not been called yet, it also calls WriteHeader("ok").
    Write(data []byte) (int, error)
}

ResponseWriter is used by a CNP server to write responses to CNP requests.

type Server Uses

type Server struct {
    // LogAccess is called for every finished response if it's non-nil.
    LogAccess func(resp ResponseWriter, req *Request, respIntent string, respBytes int64)

    // LogError is called when an error happens if it's non-nil.
    LogError func(err interface{})

    // AccessLog is used to log finished responses if LogAccess is nil.
    AccessLogger *log.Logger

    // ErrorLogger is used to log errors if LogError is nil.
    ErrorLogger *log.Logger

    // Address is the host:port that the server listens on.
    Address string

    // Handler is used to handle received requests.
    Handler Handler

    // Validate enables request parameter value validation; invalid requests
    // are responded to with errors.
    Validate bool
    // contains filtered or unexported fields
}

Server represents a CNP server.

func NewServer Uses

func NewServer() *Server

NewServer creates a new Server with default access and errors loggers, validation enabled and the listen address set to "localhost".

func (*Server) HandleConn Uses

func (srv *Server) HandleConn(conn net.Conn)

HandleConn reads a CNP request from conn and runs a handler to respond.

func (*Server) ListenAndServe Uses

func (srv *Server) ListenAndServe() error

ListenAndServe uses net.Listen to listen on TCP srv.Address for new requests, then calls srv.Serve.

func (*Server) Serve Uses

func (srv *Server) Serve(l net.Listener) error

Serve listens on l for new connections and dispatches HandleConn goroutines.

Package cnp imports 15 packages (graph). Updated 2017-09-18. Refresh now. Tools for package owners.