-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
65 lines (58 loc) · 1.23 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
package main
import (
"log"
"strings"
"github.com/srinkco/srink/utils/apierrors"
apiutil "github.com/srinkco/srink/utils/apiutils"
"github.com/valyala/fasthttp"
)
type client struct {
conf *config
log *log.Logger
apiUrl string
}
func newClient(l *log.Logger) *client {
c := &client{
log: l,
}
c.readConfig()
c.apiUrl = strings.TrimSuffix(
c.conf.getString("api-url"),
"/",
)
return c
}
func (c *client) updateApiUrl(apiUrl string) {
apiUrl = strings.TrimSuffix(apiUrl, "/")
c.apiUrl = apiUrl
c.conf.add("api-url", apiUrl)
c.conf.write()
}
func (c *client) readConfig() {
c.conf = readUserConfig("client-conf.yml", c.log)
c.conf.tryAdd("api-url", DEFAULT_API_URL)
c.conf.write()
}
func (c *client) shortenUrl(hash, url string) (string, error) {
args := fasthttp.AcquireArgs()
args.Add("hash", hash)
args.Add("url", url)
args.Add("token", c.conf.getString("token"))
defer fasthttp.ReleaseArgs(args)
code, body, err := fasthttp.Post(
nil,
strings.Join(
[]string{c.apiUrl, "api/new"},
"/",
),
args,
)
if err != nil {
return "", err
}
resp := apiutil.UnmarshalResponse(body)
if code != 200 {
return "", apierrors.New("shorten url", code, resp.Description)
}
return resp.ShortenedUrl, nil
}