forked from coaidev/chatnio-api-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.go
76 lines (63 loc) · 1.52 KB
/
instance.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 chatnio
import (
"fmt"
"github.com/whitiy666/chatnio-api-go/utils"
"os"
"strings"
)
type Instance struct {
ApiKey string
Endpoint string
}
func (i *Instance) GetApiKey() string {
return i.ApiKey
}
func (i *Instance) GetEndpoint() string {
if i.Endpoint == "" {
return "https://api.chatnio.net"
}
return i.Endpoint
}
func (i *Instance) SetApiKey(apiKey string) {
i.ApiKey = apiKey
}
func (i *Instance) SetEndpoint(endpoint string) {
if strings.HasSuffix(endpoint, "/") {
endpoint = strings.TrimSuffix(endpoint, "/")
}
i.Endpoint = endpoint
}
func (i *Instance) GetChatApiKey() string {
if !i.IsAuthenticated() {
return "anonymous"
}
return i.ApiKey
}
func (i *Instance) IsAuthenticated() bool {
return strings.TrimSpace(i.ApiKey) != ""
}
func (i *Instance) GetChatEndpoint() string {
host := utils.TrimPrefixes(i.GetEndpoint(), "http://", "https://")
return fmt.Sprintf("wss://%s/chat", host)
}
func (i *Instance) GetHeaders() utils.Headers {
return utils.Headers{
"Authorization": fmt.Sprintf("Bearer %s", i.GetApiKey()),
"Content-Type": "application/json",
"Accept": "application/json",
}
}
func (i *Instance) Mix(path string) string {
return i.GetEndpoint() + path
}
// NewInstance creates a new instance of the chatnio client
func NewInstance(key string) *Instance {
return &Instance{
ApiKey: key,
}
}
// NewInstanceFromEnv creates a new instance of the chatnio client from the environment
func NewInstanceFromEnv(env string) *Instance {
key := os.Getenv(env)
return NewInstance(key)
}