-
Notifications
You must be signed in to change notification settings - Fork 2
/
recipe.go
57 lines (46 loc) · 1.25 KB
/
recipe.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
package recipe
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
dperrors "github.com/ONSdigital/dp-api-clients-go/v2/errors"
"github.com/ONSdigital/log.go/v2/log"
)
// GetRecipe from an ID
func (c *Client) GetRecipe(ctx context.Context, userAuthToken, serviceAuthToken, recipeID string) (*Recipe, error) {
uri := fmt.Sprintf("%s/recipes/%s", c.hcCli.URL, recipeID)
res, err := c.doGetWithAuthHeaders(ctx, userAuthToken, serviceAuthToken, uri)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to get response from Recipe API: %s", err),
http.StatusInternalServerError,
nil,
)
}
defer closeResponseBody(ctx, res)
if res.StatusCode != http.StatusOK {
return nil, c.errorResponse(res)
}
var recipe Recipe
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to read response body: %s", err),
res.StatusCode,
log.Data{"response_body": string(b)},
)
}
if len(b) == 0 {
b = []byte("[response body empty]")
}
if err := json.Unmarshal(b, &recipe); err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to unmarshal response body: %s", err),
http.StatusInternalServerError,
log.Data{"response_body": string(b)},
)
}
return &recipe, nil
}