-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_responseprocessor_test.go
More file actions
65 lines (57 loc) · 1.66 KB
/
example_responseprocessor_test.go
File metadata and controls
65 lines (57 loc) · 1.66 KB
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
65
package cliware_test
import (
"fmt"
"net/http"
"net/url"
c "github.com/delicb/cliware"
)
// HTTPError is struct holding information about HTTP response that went wrong.
type HTTPError struct {
Status string
StatusCode int
URL string
Method string
}
// Error is implementation of error interface for HTTPError.
func (h *HTTPError) Error() string {
return fmt.Sprintf("%s %s (%d %s)", h.Method, h.URL, h.StatusCode, h.Status)
}
// statusCodeToError is middleware that inspects HTTP response and if its
// response code is higher or equal to 400 creates HTTPError instance and
// passes it down the chain with response relevant response information.
func statusCodeToError() c.Middleware {
return c.ResponseProcessor(func(resp *http.Response, err error) error {
// no further processing if we already got error, but in different
// middleware we can inspect error, replace it or suppress it
if err != nil {
return err
}
if resp.StatusCode >= 400 {
return &HTTPError{
Status: resp.Status,
StatusCode: resp.StatusCode,
URL: resp.Request.URL.String(),
Method: resp.Request.Method,
}
}
return nil
})
}
// notFoundResponse is helper method that always returns HTTP response with
// 404 Not Found status.
func notFoundResponse(req *http.Request) (*http.Response, error) {
return &http.Response{
Status: http.StatusText(http.StatusNotFound),
StatusCode: http.StatusNotFound,
Request: &http.Request{
URL: &url.URL{
Path: "/some_path",
},
Method: "GET",
},
}, nil
}
func ExampleResponseProcessor() {
_, err := statusCodeToError().Exec(c.HandlerFunc(notFoundResponse)).Handle(nil)
fmt.Println(err)
}