github.com/ashleymcnamara/buffalo@v0.8.0/app.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"net/http"
     5  	"sync"
     6  
     7  	gcontext "github.com/gorilla/context"
     8  	"github.com/gorilla/mux"
     9  	"github.com/markbates/refresh/refresh/web"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // App is where it all happens! It holds on to options,
    14  // the underlying router, the middleware, and more.
    15  // Without an App you can't do much!
    16  type App struct {
    17  	Options
    18  	// Middleware returns the current MiddlewareStack for the App/Group.
    19  	Middleware    *MiddlewareStack
    20  	ErrorHandlers ErrorHandlers
    21  	router        *mux.Router
    22  	moot          *sync.Mutex
    23  	routes        RouteList
    24  	root          *App
    25  }
    26  
    27  func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    28  	defer gcontext.Clear(r)
    29  	ws := &buffaloResponse{
    30  		ResponseWriter: w,
    31  	}
    32  	if a.MethodOverride != nil {
    33  		a.MethodOverride(w, r)
    34  	}
    35  	var h http.Handler
    36  	h = a.router
    37  	if a.Env == "development" {
    38  		h = web.ErrorChecker(h)
    39  	}
    40  	h.ServeHTTP(ws, r)
    41  }
    42  
    43  // New returns a new instance of App, without any frills
    44  // or thrills. Most people will want to use Automatic which
    45  // adds some sane, and useful, defaults.
    46  func New(opts Options) *App {
    47  	opts = optionsWithDefaults(opts)
    48  
    49  	a := &App{
    50  		Options:    opts,
    51  		Middleware: newMiddlewareStack(),
    52  		ErrorHandlers: ErrorHandlers{
    53  			404: NotFoundHandler,
    54  			500: defaultErrorHandler,
    55  		},
    56  		router: mux.NewRouter(),
    57  		moot:   &sync.Mutex{},
    58  		routes: RouteList{},
    59  	}
    60  	a.router.NotFoundHandler = http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
    61  		c := a.newContext(RouteInfo{}, res, req)
    62  		err := errors.Errorf("path not found: %s", req.URL.Path)
    63  		a.ErrorHandlers.Get(404)(404, err, c)
    64  	})
    65  
    66  	return a
    67  }
    68  
    69  // Automatic returns a new instance of App with sane defaults,
    70  // some not so sane defaults, and a few bits and pieces to make
    71  // your life that much easier. You'll want to use this almost
    72  // all of the time to build your applications.
    73  //
    74  // https://www.youtube.com/watch?v=BKbOplYmjZM
    75  func Automatic(opts Options) *App {
    76  	opts = optionsWithDefaults(opts)
    77  
    78  	a := New(opts)
    79  
    80  	if a.MethodOverride == nil {
    81  		a.MethodOverride = MethodOverride
    82  	}
    83  
    84  	a.Use(RequestLogger)
    85  
    86  	return a
    87  }