-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurlshortener.go
More file actions
115 lines (108 loc) · 2.38 KB
/
urlshortener.go
File metadata and controls
115 lines (108 loc) · 2.38 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
114
115
package urlshortener
import (
"bytes"
"json"
"http"
"io/ioutil"
"os"
"strings"
)
func ShortenURL(longUrl string) (shortenUrl string, err os.Error) {
var encbuf bytes.Buffer
enc := json.NewEncoder(&encbuf)
err = enc.Encode(map[string]string{"longUrl": longUrl})
if err != nil {
return
}
res, err := http.Post("https://www.googleapis.com/urlshortener/v1/url", "application/json", strings.NewReader(encbuf.String()))
if err != nil {
return
}
if res.StatusCode != 200 {
err = os.NewError("failed to post")
return
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
var decbuf bytes.Buffer
decbuf.Write(b)
dec := json.NewDecoder(&decbuf)
var out map[string]interface{}
err = dec.Decode(&out)
if err != nil {
return
}
shortenUrl = out["id"].(string)
return
}
func ExpandURL(shortUrl string) (expandedUrl string, err os.Error) {
param := http.EncodeQuery(map[string][]string{"shortUrl": {shortUrl}})
res, _, err := http.Get("https://www.googleapis.com/urlshortener/v1/url?" + param)
if err != nil {
return
}
if res.StatusCode != 200 {
err = os.NewError("failed to post")
return
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
var decbuf bytes.Buffer
decbuf.Write(b)
dec := json.NewDecoder(&decbuf)
var out map[string]interface{}
err = dec.Decode(&out)
if err != nil {
return
}
expandedUrl = out["longUrl"].(string)
return
}
type AnalyticsCount struct {
Count string
Id string
}
type AnalyticsItem struct {
ShortUrlClicks string
LongUrlClicks string
Referrers []AnalyticsCount
Countries []AnalyticsCount
Browsers []AnalyticsCount
Platforms []AnalyticsCount
}
type AnalyticsInfo struct {
Kind string
Id string
LongUrl string
Status string
Created string
Analytics struct {
AllTime AnalyticsItem
Month AnalyticsItem
Week AnalyticsItem
Day AnalyticsItem
TwoHours AnalyticsItem
}
}
func AnalyticsURL(shortUrl string) (info AnalyticsInfo, err os.Error) {
param := http.EncodeQuery(map[string][]string{"shortUrl": {shortUrl}, "projection": {"FULL"}})
var res *http.Response
res, _, err = http.Get("https://www.googleapis.com/urlshortener/v1/url?" + param)
if err != nil {
return
}
if res.StatusCode != 200 {
err = os.NewError("failed to post")
return
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
err = json.Unmarshal(b, &info)
return
}