-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitly.go
More file actions
64 lines (53 loc) · 1.3 KB
/
bitly.go
File metadata and controls
64 lines (53 loc) · 1.3 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
const bitlyAPIRoot = "https://api-ssl.bitly.com"
//shortenURL returns the original url if there's an error
func shortenURL(longURL string) (shortURL string) {
if config.BitlyKey == "" || config.BitlyKey == "{your key here}" {
return longURL
}
safeURL := url.QueryEscape(longURL)
apiURL := bitlyAPIRoot + fmt.Sprintf("/v3/shorten?access_token=%s&longUrl=%s", config.BitlyKey, safeURL)
// Build the request
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
log.Println("bit.ly error: ", err)
return longURL
}
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Do(req)
if err != nil {
log.Println("Do: ", err)
return longURL
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return longURL
}
var response bitly
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
log.Println(err)
return longURL
}
return response.Data.URL
}
type bitly struct {
StatusCode int `json:"status_code"`
StatusTxt string `json:"status_txt"`
Data struct {
URL string `json:"url"`
Hash string `json:"hash"`
GlobalHash string `json:"global_hash"`
LongURL string `json:"long_url"`
NewHash int `json:"new_hash"`
} `json:"data"`
}