-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutil.go
63 lines (52 loc) · 1.45 KB
/
util.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
package request
// todo: put all of this somewhere more common
import (
"encoding/json"
"errors"
"net/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
successJsonKey = "success"
errorJsonKey = "error"
)
type GenericApiResponseBody map[string]any
func NewGenericApiSuccessResponseBody() GenericApiResponseBody {
return map[string]any{
successJsonKey: true,
}
}
func NewGenericApiFailureResponseBody(err error) GenericApiResponseBody {
return map[string]any{
successJsonKey: false,
errorJsonKey: err.Error(),
}
}
func (b *GenericApiResponseBody) ToString() string {
marshalled, _ := json.Marshal(b)
return string(marshalled)
}
func HandleGrpcErrorInWebContext(w http.ResponseWriter, err error) (int, error) {
if err == nil {
return http.StatusOK, nil
}
statusErr, ok := status.FromError(err)
if !ok {
return http.StatusInternalServerError, errors.New("internal server error")
}
switch statusErr.Code() {
case codes.OK:
return http.StatusOK, nil
case codes.InvalidArgument:
return http.StatusBadRequest, err
case codes.Unauthenticated:
return http.StatusUnauthorized, errors.New("authentication failed")
case codes.PermissionDenied:
return http.StatusForbidden, errors.New("permission denied")
case codes.Canceled, codes.DeadlineExceeded:
return http.StatusRequestTimeout, errors.New("request timed out")
default:
return http.StatusInternalServerError, errors.New("internal server error")
}
}