/
vvt.go
131 lines (111 loc) · 2.39 KB
/
vvt.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"golang.org/x/crypto/ssh/terminal"
)
type Paste struct {
Code string `json:"code"`
Encrypted bool `json:"encrypted"`
Language string `json:"language"`
Slug string `json:"slug"`
}
// Get paste from api by passing slug
// Will prompt password if paste is encrypted
func GetPaste(slug string) string {
url := "https://vvt.nu/" + slug + ".json"
result, err := http.Get(url)
if err != nil {
panic(err)
}
defer result.Body.Close()
body, err := ioutil.ReadAll(result.Body)
if err != nil {
panic(err)
}
paste := decodeJSON(body)
// Move this logix out of GetPaste..
if paste.Encrypted == true {
fmt.Printf("This paste is encrypted, enter password: ")
password, err := terminal.ReadPassword(0)
if err != nil {
panic(err)
}
fmt.Print("\n")
content, err := Decrypt(paste.Code, string(password))
if err != nil {
panic(err)
}
return content
}
return paste.Code
}
// Post paste trought api requires string and retunrs Paste object
func PostPaste(content string) Paste {
data := Paste{Code: content, Encrypted: false}
body, err := json.Marshal(data)
if err != nil {
panic(err)
}
resp, err := http.Post("https://vvt.nu/save.json", "application/json", bytes.NewReader(body))
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
paste := decodeJSON(body)
return paste
}
// decode vvt's json response to struct
func decodeJSON(s []byte) Paste {
var paste Paste
if err := json.Unmarshal(s, &paste); err != nil {
panic(err)
fmt.Printf("Hmm.. problem")
os.Exit(1)
}
return paste
}
func main() {
outputFile := flag.String("o", "", "Output file (defaul is stdout)")
flag.Parse()
args := flag.Args()
switch len(args) {
case 0:
if !terminal.IsTerminal(0) {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
paste := PostPaste(string(bytes))
fmt.Printf("https://vvt.nu/" + paste.Slug + "\n")
} else {
fmt.Println("No piped data")
flag.Usage()
return
}
case 1:
content := GetPaste(args[0])
if *outputFile != "" {
file, err := os.Create(*outputFile)
if err != nil {
panic(err)
}
file.WriteString(content)
fmt.Println(*outputFile + " created")
} else {
fmt.Println(content)
}
default:
flag.Usage()
os.Exit(-1)
}
}