-
Notifications
You must be signed in to change notification settings - Fork 0
/
getContextValue.go
45 lines (36 loc) · 1.13 KB
/
getContextValue.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
package apihelper
import (
"context"
"fmt"
"net/http"
"github.com/hodl-repos/pdf-invoice/pkg/standardisedError"
)
// define custom error to catch later in withErrorHandler
type GetContextValueError struct {
standardisedError.StandardisedError
Param string `json:"param"`
}
func (m *GetContextValueError) Error() string {
return fmt.Sprintf("cannot load context value from %v", m.Param)
}
func (m *GetContextValueError) GetStandardisedError() *standardisedError.StandardisedError {
return &m.StandardisedError
}
func GetContextValue[T any](ctx context.Context, valueKey string) (*T, error) {
v, ok := ctx.Value(valueKey).(T)
if !ok {
return nil, &GetContextValueError{
Param: valueKey,
StandardisedError: generateStandardisedErrorMarshal(),
}
}
return &v, nil
}
func generateStandardisedErrorMarshal() standardisedError.StandardisedError {
return standardisedError.StandardisedError{
Type: "https://example.net/internal-error",
Title: "Could not load the route-param from the content[value]",
Status: http.StatusInternalServerError,
Detail: "Could not load the route-param from the content[value]",
}
}