-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
67 lines (56 loc) · 1.17 KB
/
client.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
package extractor
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"go.formulabun.club/extractor/env"
"go.formulabun.club/metadatadb"
)
type Client struct {
c *http.Client
buff []metadatadb.File
}
func NewClient() *Client {
var capacity = 5
c := Client{
http.DefaultClient,
make([]metadatadb.File, 0, capacity),
}
return &c
}
func (c *Client) ExtractFile(data metadatadb.File) error {
var err error
if len(c.buff) == cap(c.buff) {
if err = c.ExtractFiles(c.buff); err != nil {
return err
}
c.buff = c.buff[:0]
} else {
c.buff = append(c.buff, data)
}
return nil
}
func (c *Client) ExtractFiles(data []metadatadb.File) error {
if len(data) == 0 {
return nil
}
buf := bytes.Buffer{}
enc := json.NewEncoder(&buf)
enc.Encode(data)
resp, err := c.c.Post("http://"+env.Host, "application/json", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
body, err := io.ReadAll(resp.Body)
return errors.Join(fmt.Errorf("Bad request: %s", body), err)
}
if resp.StatusCode != http.StatusAccepted {
return errors.New("Unknown error in the extractor server")
}
return nil
}