-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhardwares.go
60 lines (49 loc) · 1.21 KB
/
hardwares.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
package main
import (
"fmt"
"os"
"github.com/gofiber/fiber/v2"
"gopkg.in/yaml.v3"
apiv1 "github.com/nicklasfrahm/infrastructure/api/v1"
)
const (
repository = "nicklasfrahm/infrastructure"
fileURLTemplate = "https://raw.githubusercontent.com/%s/main/%s"
)
// Hardware returns a fiber app for the hardware resource.
func Hardware(useRemote bool) *fiber.App {
app := fiber.New()
app.Get("/:name<alpha>", func(c *fiber.Ctx) error {
name := c.Params("name")
var bytes []byte
var err error
path := fmt.Sprintf("config/hardwares/%s.yaml", name)
if useRemote {
// Use the GitHub API to fetch the file.
path = fmt.Sprintf(fileURLTemplate, repository, path)
status, body, errs := fiber.Get(path).Bytes()
if len(errs) > 0 {
return errs[0]
}
if status != 200 {
if status == 404 {
return c.Next()
}
return fmt.Errorf("failed to fetch file: %s", path)
}
bytes = body
} else {
// Use the local file system to fetch the file.
bytes, err = os.ReadFile(path)
if err != nil {
return err
}
}
hardware := &apiv1.Hardware{}
if err := yaml.Unmarshal(bytes, hardware); err != nil {
return err
}
return c.Status(200).JSON(hardware)
})
return app
}