-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortener.go
42 lines (35 loc) · 858 Bytes
/
shortener.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
package goadfly
import (
"encoding/json"
"errors"
"net/url"
)
// ShortenLink - shorten new link
func (c *Client) ShortenLink(urlToShorten string) (string, error) {
endpoint := apiURL + "shorten"
params := url.Values{}
params.Add("url", urlToShorten)
response, err := c.sendPostRequest(endpoint, params)
if err != nil {
return "", err
}
result := adflyLinkShortenResponse{}
err = json.Unmarshal(response, &result)
if err != nil {
return "", err
}
// find first error
if len(result.Errors) > 0 {
for _, firstError := range result.Errors {
errMsg := firstError.Messsage
if firstError.Messsage == "" {
errMsg = "unknown error"
}
return "", errors.New(errMsg)
}
}
for _, firstURLResult := range result.Data {
return firstURLResult.ShortURL, nil
}
return "", errors.New("failed to find short url in response")
}