hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/internal/fabric/fabric.go
blob: 3e52e6f0786b3a2d1e4cdc66183cfe95b349c8f1 (plain)
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
72
73
74
75
76
77
78
79
package fabric

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

const (
	apiBase   = "https://meta.fabricmc.net/v2"
	userAgent = "benson/2.0 (github.com/hachem-wtf/benson)"
)

type GameVersion struct {
	Version string `json:"version"`
	Stable  bool   `json:"stable"`
}

type LoaderVersion struct {
	Version string `json:"version"`
	Stable  bool   `json:"stable"`
}

type InstallerVersion struct {
	Version string `json:"version"`
	Stable  bool   `json:"stable"`
}

type Client struct {
	http *http.Client
}

func NewClient() *Client {
	return &Client{http: &http.Client{Timeout: 30 * time.Second}}
}

func (c *Client) get(path string, out any) error {
	req, err := http.NewRequest(http.MethodGet, apiBase+path, nil)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", userAgent)

	resp, err := c.http.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("fabric: %s returned %s", path, resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(out)
}

func (c *Client) GameVersions() ([]GameVersion, error) {
	var versions []GameVersion
	if err := c.get("/versions/game", &versions); err != nil {
		return nil, err
	}
	return versions, nil
}

func (c *Client) LoaderVersions() ([]LoaderVersion, error) {
	var versions []LoaderVersion
	if err := c.get("/versions/loader", &versions); err != nil {
		return nil, err
	}
	return versions, nil
}

func (c *Client) InstallerVersions() ([]InstallerVersion, error) {
	var versions []InstallerVersion
	if err := c.get("/versions/installer", &versions); err != nil {
		return nil, err
	}
	return versions, nil
}