Giter Site home page Giter Site logo

respond's Introduction

respond GoDoc

Get it:

go get gopkg.in/matryer/respond.v1

Import it:

import (
  "gopkg.in/matryer/respond.v1"
)

Use it:

respond.With(w, r, http.StatusOK, data)

Package respond provides low-touch API responses for Go data services.

  • Idiomatic way of responding to data APIs using respond.With
  • Use respond.With to respond with default options, or make a respond.Options for advanced features
  • Encoder abstraction lets you easily speak different formats
  • Before and After function fields allow you to envelope and mutate data, set common HTTP headers, log activity etc.
  • Protected against multiple responses

Usage

The simplest use of respond is to just call respond.With inside your handlers:

func handleSomething(w http.ResponseWriter, r *http.Request) {
	
	data, err := loadFromDB()
	if err != nil {

		// respond with an error
		respond.With(w, r, http.StatusInternalServerError, err)
		return // always return after responding

	}

	// respond with OK, and the data
	respond.With(w, r, http.StatusOK, data)

}

To tweak the behaviour of respond.With you can wrap the handler with a respond.Options:

func main() {
	
	opts := &respond.Options{
		// options go here
	}
	http.Handle("/foo", opts.Handler(fooHandler))
	log.Fatal(http.ListenAndServe(":8080", nil))

}

Use respond.With as normal.

For a complete list of options, see the API documentation for respond.Options.

respond's People

Contributors

matryer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

respond's Issues

Responding 204 leads to panic

Using HTTP status code 204 "No Content" to indicate that a request was successfully processed but no data is being returned leads to a panic.

 
 -> gopkg.in/matryer/respond%2ev1.with
 ->   /home/david/go/pkg/mod/gopkg.in/matryer/[email protected]/respond.go:33

    gopkg.in/matryer/respond%2ev1.WithStatus
      /home/david/go/pkg/mod/gopkg.in/matryer/[email protected]/respond.go:76
    main.UserListOne
      /home/david/dev/wfi_api/user.go:123
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5.(*Mux).routeHTTP
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:442
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5/middleware.Timeout.func1.1
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/timeout.go:45
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5/middleware.Recoverer.func1
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/recoverer.go:38
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5/middleware.RequestID.func1
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/request_id.go:76
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5/middleware.RealIP.func1
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/realip.go:35
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5/middleware.RequestLogger.func1.1
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/middleware/logger.go:57
    net/http.HandlerFunc.ServeHTTP
      /usr/local/go/src/net/http/server.go:2047
    github.com/go-chi/chi/v5.(*Mux).ServeHTTP
      /home/david/go/pkg/mod/github.com/go-chi/chi/[email protected]/mux.go:88
    net/http.serverHandler.ServeHTTP
      /usr/local/go/src/net/http/server.go:2879
    net/http.(*conn).serve
      /usr/local/go/src/net/http/server.go:1930
    created by net/http.(*Server).Serve
      /usr/local/go/src/net/http/server.go:3034```

respond.Before unable to find original request with Go1.7+ native Context

Due to the changes in Go1.7+ and the implementation of a native Context, the respond.Before operation fails due to the original request being duplicated within WithContext and not available to the Before handler.

Example:

func (r *Request) WithContext(ctx context.Context) *Request {
    if ctx == nil {
        panic("nil context")
    }

    r2 := new(Request)
    *r2 = *r
    r2.ctx = ctx
    return r2
}

This sample code will not be able to access the original data object to resolve the .Public interface:

responder.Before = func(w http.ResponseWriter, r *http.Request, status int, data interface{}) (int, interface{}) {
        if err, ok := data.(error); ok {
            return status, map[string]interface{}{"error": err.Error()}
        }
        if obj, ok := data.(interface {
            Public() interface{}
        }); ok {
            return status, obj.Public()
        }
        return status, data
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.