response

package module
v0.0.0-...-82af245 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2018 License: MIT Imports: 5 Imported by: 8

README

Response

GoDoc Build Status Maintainability Test Coverage

Go library for wrapping HTTP responses.

Example

The basic usage changes the http.HandleFunc slightly. Instead of taking a request and a response writer, you take a request and return a response object. This allows a more linear flow of logic through http handlers as responses are values instead of side-effects.

The basic usage is shown below.

emptyHandler := func (r *http.Request) response.Response {
    return response.Empty(http.StatusNoContent)
}

http.HandleFunc("/empty", response.Convert(emptyHandler))

There are several convenience constructors like the JSON response constructor shown below. This example serializes a map into a JSON object and sets additional headers.

func (r *http.Request) response.Response {
    resp := response.JSON(map[string]interface{}{
        "foo": "bar",
        "baz": []int{3, 4, 5},
    })

    resp.AddHeader("Location", "/foo/bar/baz")
    resp.AddHeader("X-Request-ID", "1234-567")
    return resp
}

There is also support for attaching a reader for streaming a response body. This is useful if responses are very large or infinite (for example, a media server or an endpoint that returns server-sent events).

func (r *http.Request) response.Response {
    ch := make(chan int)

    go func() {
        for n := range ch {
            fmt.Printf("Sent an additional %d bytes of data\n", n)
        }
    }()

    return response.Stream(
        reader,               // Body content (read closer)
        WithProgressChan(ch), // Monitor how much data was sent to client
        WithFlush(),          // Enable flushing after every write (32k chunks)
    )
}

The Stream constructor will watch for client disconnect and discontinue calling the reader for additional data.

License

Copyright (c) 2017 Eric Fritz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Convert

func Convert(f HandlerFunc) http.HandlerFunc

Convert converts a HandlerFunc to an http.HandlerFunc.

func Serialize

func Serialize(r Response) (http.Header, []byte, error)

Serialize reads the entire response and returns the headers and a byte slice containing the content of the entire body. An error is returned if writing to the response recorder fails.

Types

type CallbackFunc

type CallbackFunc func(error)

CallbackFunc receives the value of errors which occur when the body fails to write to the remote end.

type HandlerFunc

type HandlerFunc func(*http.Request) Response

HandlerFunc is an analog of an http.HandlerFunc that returns a response object instead of writing directly to a ResponseWriter.

type Response

type Response interface {
	// StatusCode retrieves the status code of the response.
	StatusCode() int

	// Header retrieves the first value set to this header.
	Header(header string) string

	// SetStatusCode sets the status code of the response.
	SetStatusCode(statusCode int) Response

	// SetHeader sets the value of this header.
	SetHeader(header, val string) Response

	// AddHeader adds another value to this header.
	AddHeader(header, val string) Response

	// AddCallback registers a callback to be invoked on after
	// the entire response body has been written to the client.
	AddCallback(f CallbackFunc) Response

	// DecorateWriter wraps a function around the underlying io.Writer
	// which writes the response body content.
	DecorateWriter(f WriterDecorator) Response

	// WriteTo writes the response data to the ResponseWriter. This method
	// consumes the body content and will panic when called multiple times.
	WriteTo(w http.ResponseWriter)
}

Response wraps a payload returned from an HTTP handler function.

func Empty

func Empty(statusCode int) Response

Empty creates an empty response with the given status code.

func JSON

func JSON(data interface{}) Response

JSON creates a response with the data serialized as JSON for the body.

func Reconstruct

func Reconstruct(statusCode int, headers http.Header, body []byte) Response

Reconstruct creates a response from the values returned from Serialize.

func Respond

func Respond(data []byte) Response

Respond creates a response with the given body.

func Stream

func Stream(rc io.ReadCloser, configs ...StreamConfigFunc) Response

Stream creates a response that writes the data from the given reader. The reader is closed once all data is consumed, an error is encountered, or the client disconnects.

type StreamConfigFunc

type StreamConfigFunc func(*streamConfig)

StreamConfigFunc is a function used to configure the Stream constructor.

func WithFlush

func WithFlush() StreamConfigFunc

WithFlush instructs Stream to call the writer's Flush method after every successful chunk of data is written.

func WithProgressChan

func WithProgressChan(progress chan<- int) StreamConfigFunc

WithProgressChan instructs Stream to send the number of bytes written to this chan after every successful chunk of data is written. Consumers of this channel should be efficient as this write will block progress. This channel is closed by the WriteTo method.

type WriterDecorator

type WriterDecorator func(io.Writer) io.Writer

WriterDecorator returns an io.Writer that writes to the given io.Writer.

type WriterFunc

type WriterFunc func([]byte) (int, error)

WriterFunc is a function

func (WriterFunc) Write

func (f WriterFunc) Write(p []byte) (int, error)

Write implements the io.Writer interface.

Jump to

Keyboard shortcuts

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