/
ClipShorter.go
104 lines (84 loc) · 1.95 KB
/
ClipShorter.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/atotto/clipboard"
"io/ioutil"
"log"
"net/http"
"strings"
)
var readerChan chan string
var writerChan chan string
var shortenChan chan string
// needed to extract shortened url from google
type apiData struct {
Kind, Id, LongUrl string
}
func main() {
readerChan = make(chan string)
writerChan = make(chan string)
shortenChan = make(chan string)
fmt.Println("ClipShorter now watches the clipboard.")
// start reading the clipboard in an endless loop
go func() {
for {
readClipBoard()
}
}()
// start shortening service in an endless loop
go func() {
for {
shortUrl()
}
}()
// start writing to the clipboard in an endless loop
go func() {
for {
writeClipBoard()
}
}()
for {
fmt.Printf("%s", <-writerChan)
}
}
func readClipBoard() {
clip, _ := clipboard.ReadAll()
if isUrl(clip) && len(clip) > 50 {
readerChan <- clip
}
}
func shortUrl() {
url := <-readerChan
googleApiUrl := "https://www.googleapis.com/urlshortener/v1/url"
body := bytes.NewBufferString(fmt.Sprintf(`{"longUrl": "%s"}`, url))
request, _ := http.NewRequest("POST", googleApiUrl, body)
request.Header.Add("Content-Type", "application/json")
client := http.Client{}
response, _ := client.Do(request)
output, _ := ioutil.ReadAll(response.Body)
response.Body.Close()
var data apiData
json.Unmarshal(output, &data)
shortenChan <- data.Id
}
func writeClipBoard() {
shortened := <-shortenChan
err := clipboard.WriteAll(shortened)
if err != nil {
log.Fatal(err)
}
writerChan <- "wrote " + shortened + " to the clipboard\n"
}
func isUrl(url string) bool {
// base case: already shortened
if strings.Contains(url, "goo.gl") {
return false
}
// check if is valid url
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
return true
}
return false
}