-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
80 lines (64 loc) · 2.09 KB
/
http.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package utils
import (
"context"
"fmt"
"net/http"
"time"
"unicode"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// --------------------------------------------------------------------------------------------------------------------
type HttpError struct {
StatusCode codes.Code
Response string
Headers map[string]string
}
func (e *HttpError) Error() string {
return fmt.Sprintf("status %d: %s", e.StatusCode, e.Response)
}
// WrapErr wraps the given error into a new one that contains the given status code and response
func WrapErr(statusCode codes.Code, res string) *HttpError {
return &HttpError{
StatusCode: statusCode,
Response: res,
}
}
func (e *HttpError) WithHeaders(headers map[string]string) *HttpError {
e.Headers = headers
return e
}
// --------------------------------------------------------------------------------------------------------------------
func NewTooManyRequestsError(res string) *HttpError {
// Compute when the user will be able to retry
currentTime := time.Now().UTC()
nextDayMidnight := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day()+1, 0, 0, 0, 0, time.UTC)
retryAfter := nextDayMidnight.Sub(currentTime).Seconds()
return WrapErr(codes.ResourceExhausted, res).WithHeaders(map[string]string{
http.CanonicalHeaderKey("Retry-After"): fmt.Sprintf("%d", int(retryAfter)),
})
}
// --------------------------------------------------------------------------------------------------------------------
func ucFirst(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
func UnwrapError(ctx context.Context, err error) error {
if statusError, ok := status.FromError(err); ok {
return statusError.Err()
}
if httpErr, ok := err.(*HttpError); ok {
if len(httpErr.Headers) != 0 {
err := grpc.SendHeader(ctx, metadata.New(httpErr.Headers))
if err != nil {
return err
}
}
return status.Error(httpErr.StatusCode, httpErr.Response)
}
return status.Error(codes.Internal, ucFirst(err.Error()))
}