-
Notifications
You must be signed in to change notification settings - Fork 69
/
recipe_file.go
71 lines (55 loc) · 1.57 KB
/
recipe_file.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
package recipes
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"gopkg.in/yaml.v2"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
type RecipeFileFetcher struct {
HTTPGetFunc func(string) (*http.Response, error)
readFileFunc func(string) ([]byte, error)
}
func NewRecipeFileFetcher() *RecipeFileFetcher {
f := RecipeFileFetcher{}
f.HTTPGetFunc = defaultHTTPGetFunc
f.readFileFunc = defaultReadFileFunc
return &f
}
func defaultHTTPGetFunc(recipeURL string) (*http.Response, error) {
return http.Get(recipeURL)
}
func defaultReadFileFunc(filename string) ([]byte, error) {
return ioutil.ReadFile(filename)
}
func (f *RecipeFileFetcher) FetchRecipeFile(recipeURL *url.URL) (*types.OpenInstallationRecipe, error) {
response, err := f.HTTPGetFunc(recipeURL.String())
if err != nil {
return nil, err
}
if response.StatusCode < 200 || response.StatusCode > 299 {
return nil, fmt.Errorf("received non-2xx status code %d when retrieving recipe", response.StatusCode)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return NewRecipeFile(string(body))
}
func (f *RecipeFileFetcher) LoadRecipeFile(filename string) (*types.OpenInstallationRecipe, error) {
out, err := f.readFileFunc(filename)
if err != nil {
return nil, err
}
return NewRecipeFile(string(out))
}
func NewRecipeFile(recipeFileString string) (*types.OpenInstallationRecipe, error) {
var f types.OpenInstallationRecipe
err := yaml.Unmarshal([]byte(recipeFileString), &f)
if err != nil {
return nil, err
}
return &f, nil
}