forked from Lebenoa/webui-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
113 lines (94 loc) · 2.26 KB
/
api.go
File metadata and controls
113 lines (94 loc) · 2.26 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package api
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
)
type api struct {
Config Config
// Auth contains username and password like this:
//
// "username, password" or you can use Username && Password field instead.
//
// But do keep in mind that if Auth is not empty string, it'll use Auth and not Username && Password
Auth string
Username string
Password string
}
var (
httpClient = &http.Client{}
API = &api{
Config: setDefault(),
}
)
func New(newConfig ...Config) *api {
API = &api{
Config: setDefault(newConfig...),
}
return API
}
// Set username and password for use when making request. Equivalent to
//
// api.Username = username
// api.Password = password
//
// Either username or password should not be empty string
func (a *api) SetAuth(username, password string) {
a.Username = username
a.Password = password
}
// Convenience function to build prompt.
//
// BuildPrompt("masterpiece", "best quality", "solo") -> "masterpiece, best quality, solo"
func BuildPrompt(args ...string) string {
return strings.Join(args, ", ")
}
// Send Get Request.
func (a *api) get(path string) (body []byte, err error) {
req, err := http.NewRequest("GET", a.Config.BaseURL+path, nil)
if err != nil {
return nil, err
}
return a.exec(req)
}
// Send Post Request.
func (a *api) post(path string, data []byte) (body []byte, err error) {
req, err := http.NewRequest("POST", a.Config.BaseURL+path, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return a.exec(req)
}
// Send Request.
func (a *api) exec(req *http.Request) ([]byte, error) {
a.setAuth(req)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
return readBody(resp)
}
// Set HTTP Basic Auth.
func (a *api) setAuth(req *http.Request) {
if a.Auth != "" {
credit := strings.Split(a.Auth, ", ")
req.SetBasicAuth(credit[0], credit[1])
} else if a.Username != "" && a.Password != "" {
req.SetBasicAuth(a.Username, a.Password)
}
}
// Read response body.
func readBody(resp *http.Response) (body []byte, err error) {
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%v", string(body))
}
return
}