~welt/murse

ref: v0.0.2 murse/client.go -rw-r--r-- 1.6 KiB
0bddb9ccwelt Revert default thread count. 5 months ago
                                                                                
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
80
81
82
83
84
85
86
87
88
89
90
91
package main

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"strconv"
	"strings"
)

type Client struct {
	repo string
	h    *http.Client
}

func NewClient(repo string) *Client {
	return &Client{
		repo: repo,
		h:    &http.Client{},
	}
}

func (c *Client) DisableHTTP2() {
	c.h.Transport = &http.Transport{
		TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),
	}
}

func (c *Client) get(url string) (io.ReadCloser, error) {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Add("User-Agent", "murse/0.0.0")

	resp, err := c.h.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return resp.Body, errors.New("got status code " + strconv.Itoa(resp.StatusCode))
	}

	return resp.Body, nil
}

func (c *Client) getRead(url string) ([]byte, error) {
	var bytes []byte
	body, err := c.get(url)
	if err != nil {
		return bytes, err
	}

	defer body.Close()

	return io.ReadAll(body)
}

func (c *Client) GetRevision(v int) ([]Change, error) {
	var changes []Change
	resp, err := c.get(c.repo + "revisions/" + strconv.Itoa(v))
	if err != nil {
		return changes, err
	}

	defer resp.Close()

	err = json.NewDecoder(resp).Decode(&changes)
	if err != nil {
		return changes, err
	}

	return changes, err
}

func (c *Client) GetObject(object string) (io.ReadCloser, error) {
	return c.get(c.repo + "objects/" + object)
}

func (c *Client) GetLatestRevision() (int, error) {
	b, err := c.getRead(c.repo + "revisions/latest")
	if err != nil {
		return -1, err
	}

	return strconv.Atoi(strings.TrimSpace(string(b)))
}