-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
59 lines (52 loc) · 1.17 KB
/
request.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
package luogu
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
func Get[T any](url string) (T, error) {
return Request[T]("GET", url, nil)
}
func Post[T any](url string, payload any) (data T, err error) {
reqBody := new(bytes.Buffer)
err = json.NewEncoder(reqBody).Encode(payload)
if err != nil {
return
}
return Request[T]("POST", url, reqBody)
}
func Request[T any](method, url string, reqBody io.Reader) (data T, err error) {
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return
}
req.Header.Add("X-Luogu-Type", "content-only")
clientId := make([]byte, 20)
if _, err = rand.Read(clientId); err != nil {
return
}
req.AddCookie(&http.Cookie{Name: "__client_id", Value: fmt.Sprintf("%040s", hex.EncodeToString(clientId))})
resp, err := new(http.Client).Do(req)
if err != nil {
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return
}
var errData ErrorResponse
if err = json.Unmarshal(body, &errData); err != nil {
return
}
if errData.Status >= 400 {
return *new(T), errors.New(errData.ErrorMessage)
}
err = json.Unmarshal(body, &data)
return
}