/
utils.go
48 lines (42 loc) · 994 Bytes
/
utils.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
package web
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
type Short struct {
URL struct {
ID string `json:"id"`
ShortURL string `json:"short_url"`
LongURL string `json:"long_url"`
ExpirationDate time.Time `json:"expiration_date"`
} `json:"url"`
Status string `json:"status"`
}
func GetBody(url string) ([]byte, error) {
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
func GetJSON(url string, v interface{}) error {
body, err := GetBody(url)
if err != nil {
return err
}
return json.Unmarshal(body, v)
}
func ShortenURL(url string) string {
client := &http.Client{}
request, _ := http.NewRequest("POST", "https://mnn.im/s", bytes.NewBufferString(url))
response, _ := client.Do(request)
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
var short Short
json.Unmarshal(body, &short)
return short.URL.ShortURL
}