/
middleware.go
64 lines (53 loc) · 1.52 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package errors
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/chances/party-server/session"
"github.com/gin-gonic/gin"
)
// HandleErrors returns Gin middleware that collates and reports reported errors
func HandleErrors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next() // Run through all handlers
numErrors := len(c.Errors)
// Bail if there are no errors
if numErrors == 0 {
return
}
allErrors := make([]*partyError, numErrors)
var code int
// Add all errors to an array, following the Errors JSON API spec
// http://jsonapi.org/format/#errors
for i, ginError := range c.Errors {
fmt.Fprintf(os.Stderr, "%s\n", ginError.Error())
// IDEA: Send the error detail and cause to some log manager?
switch ginError.Err.(type) {
case *partyError:
err := ginError.Err.(*partyError)
// On errAuth flash error to session and redirect to index on errAuth
switch err.Code {
case http.StatusSeeOther:
sesh := session.DefaultSession(c)
errorJSON, _ := json.Marshal(err)
sesh.Flash("error", string(errorJSON))
c.Redirect(err.Code, "/")
return
case http.StatusUnauthorized:
c.Header("Www-Authenticate", fmt.Sprintf(`Bearer realm="spotify", error="unauthorized", error_description="%s"`, err.Message))
}
// Otherwise add to list of errors
allErrors[i] = err
code = err.Code
default:
allErrors[i] = Internal
code = Internal.Code
}
}
// Respond with errors
c.JSON(code, partyErrors{
Errors: allErrors,
})
}
}