github.com/jasonish/buffalo@v0.8.2-0.20170413145823-bacbdd415f1b/not_found.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  
     7  	"github.com/gobuffalo/plush"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // NotFoundHandler is the default ErrorHandler for 404 responses.
    12  // In development mode it attempts to return useful debugging
    13  // information. In production it defaults to use the http.NotFound
    14  // handler.
    15  func NotFoundHandler(status int, err error, c Context) error {
    16  	env := c.Value("env")
    17  	req := c.Request()
    18  	res := c.Response()
    19  	if env != nil && env.(string) == "production" {
    20  		http.NotFound(res, req)
    21  		return nil
    22  	}
    23  	data := map[string]interface{}{
    24  		"routes": c.Value("routes"),
    25  		"method": req.Method,
    26  		"path":   req.URL.String(),
    27  		"error":  err.Error(),
    28  	}
    29  	ct := req.Header.Get("Content-Type")
    30  	if ct == "application/json" {
    31  		res.WriteHeader(404)
    32  		return json.NewEncoder(res).Encode(data)
    33  	}
    34  	ctx := plush.NewContextWith(data)
    35  	t, err := plush.Render(htmlNotFound, ctx)
    36  	if err != nil {
    37  		return errors.WithStack(err)
    38  	}
    39  	res.WriteHeader(404)
    40  	_, err = res.Write([]byte(t))
    41  	return err
    42  }
    43  
    44  var htmlNotFound = `
    45  <html>
    46  <head>
    47  	<title>404 PAGE NOT FOUND</title>
    48  	<style>
    49  		body {
    50  			font-family: helvetica;
    51  		}
    52  		table {
    53  			width: 100%;
    54  		}
    55  		th {
    56  			text-align: left;
    57  		}
    58  		tr:nth-child(even) {
    59  		  background-color: #dddddd;
    60  		}
    61  		td {
    62  			margin: 0px;
    63  			padding: 10px;
    64  		}
    65  	</style>
    66  </head>
    67  <body>
    68  <h1>404 Page Not Found!</h1>
    69  <h3>Could not find path <code>[<%= method %>] <%= path %></code></h3>
    70  <hr>
    71  <table id="buffalo-routes-table">
    72  	<thead>
    73  		<tr>
    74  			<th>METHOD</th>
    75  			<th>PATH</th>
    76  			<th>HANDLER</th>
    77  		</tr>
    78  	</thead>
    79  	<tbody>
    80  		<%= for (route) in routes { %>
    81  			<tr>
    82  				<td><%= route.Method %></td>
    83  				<td><%= route.Path %></td>
    84  				<td><code><%= route.HandlerName %></code></td>
    85  			</tr>
    86  		<% } %>
    87  	</tbody>
    88  </table>
    89  <%= if (error) { %>
    90  <hr>
    91  <h2>Error</h2>
    92  <pre><%= error %></pre>
    93  <% } %>
    94  </body>
    95  </html>
    96  `