/
main.go
67 lines (58 loc) · 1.23 KB
/
main.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
package main
import (
"os"
"fmt"
"github.com/atotto/clipboard"
"github.com/codegangsta/cli"
"io/ioutil"
"net/http"
"encoding/json"
)
func main() {
app := cli.NewApp()
app.Name = "surl"
app.Author = "Shintaro Katafuchi"
app.Email = "hot.chemistry21@gmail.com"
app.Version = "0.1.0"
app.Usage = "Shorten an url in your clipboard."
app.Action = action
app.Run(os.Args)
}
func action(context *cli.Context) {
text := readClipboard()
res := httpGet(text)
json := unmarshal(res)
if json.Errormessage != "" {
fmt.Fprintln(os.Stderr, json.Errormessage)
os.Exit(1)
}
clipboard.WriteAll(json.Shorturl)
fmt.Println("Write the value to clipboard: " + json.Shorturl)
}
func readClipboard() string {
text, err := clipboard.ReadAll()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return text
}
func httpGet(url string) []byte {
response, _ := http.Get(buildUrl(url))
body, _ := ioutil.ReadAll(response.Body)
defer response.Body.Close()
return body
}
func buildUrl(url string) string {
baseUrl := "http://is.gd/create.php?format=simple&format=json&url="
return baseUrl + url
}
func unmarshal(b []byte) data {
var d data
json.Unmarshal(b, &d)
return d
}
type data struct {
Shorturl string
Errormessage string
}