forked from andreimarcu/linx-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shorturl.go
89 lines (72 loc) · 1.83 KB
/
shorturl.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
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"github.com/zenazn/goji/web"
)
type shortenerRequest struct {
LongURL string `json:"longUrl"`
}
type shortenerResponse struct {
Kind string `json:"kind"`
ID string `json:"id"`
LongURL string `json:"longUrl"`
Error struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
func shortURLHandler(c web.C, w http.ResponseWriter, r *http.Request) {
fileName := c.URLParams["name"]
err := checkFile(fileName)
if err == NotFoundErr {
notFoundHandler(c, w, r)
return
}
metadata, err := metadataRead(fileName)
if err != nil {
oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
return
}
if metadata.ShortURL == "" {
url, err := shortenURL(getSiteURL(r) + fileName)
if err != nil {
oopsHandler(c, w, r, RespJSON, err.Error())
return
}
metadata.ShortURL = url
err = metadataWrite(fileName, &metadata)
if err != nil {
oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
return
}
}
js, _ := json.Marshal(map[string]string{
"shortUrl": metadata.ShortURL,
})
w.Write(js)
return
}
func shortenURL(url string) (string, error) {
apiURL := "https://www.googleapis.com/urlshortener/v1/url?key=" + Config.googleShorterAPIKey
jsonStr, _ := json.Marshal(shortenerRequest{LongURL: url})
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
shortenerResponse := new(shortenerResponse)
err = json.NewDecoder(resp.Body).Decode(shortenerResponse)
if err != nil {
return "", err
}
if shortenerResponse.Error.Message != "" {
return "", errors.New(shortenerResponse.Error.Message)
}
return shortenerResponse.ID, nil
}