/
main.go
76 lines (59 loc) · 1.33 KB
/
main.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
72
73
74
75
76
package main
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/kujilabo/cocotola/cocotola-tatoeba-api/src/config"
)
var timeoutImportMin = 30
func main() {
ctx := context.Background()
cfg, err := config.LoadConfig("local")
if err != nil {
panic(err)
}
url := "http://localhost:8280/v1/admin/sentence/import"
fieldname := "file"
filename := "eng_sentences_detailed.tsv"
file, err := os.Open("../cocotola-data/datasource/tatoeba/" + filename)
if err != nil {
panic(err)
}
body := bytes.Buffer{}
mw := multipart.NewWriter(&body)
fw, err := mw.CreateFormFile(fieldname, filename)
if err != nil {
panic(err)
}
if _, err := io.Copy(fw, file); err != nil {
panic(err)
}
if err = mw.Close(); err != nil {
panic(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body)
if err != nil {
panic(err)
}
req.SetBasicAuth(cfg.Auth.Username, cfg.Auth.Password)
req.Header.Set("Content-Type", mw.FormDataContentType())
client := http.Client{
Timeout: time.Duration(timeoutImportMin) * time.Minute,
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("status: %d\n", resp.StatusCode)
fmt.Printf("body: %s\n", string(respBody))
}