-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
191 lines (159 loc) · 4.82 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/genuinetools/pkg/cli"
"github.com/jessfraz/pastebinit/version"
"github.com/sirupsen/logrus"
)
var (
baseuri string
username string
password string
debug bool
)
func main() {
// Create a new cli program.
p := cli.NewProgram()
p.Name = "pastebinit"
p.Description = "Command line paste bin"
// Set the GitCommit and Version.
p.GitCommit = version.GITCOMMIT
p.Version = version.VERSION
// Build the list of available commands.
p.Commands = []cli.Command{
&serverCommand{},
}
// Setup the global flags.
p.FlagSet = flag.NewFlagSet("global", flag.ExitOnError)
p.FlagSet.StringVar(&baseuri, "b", "https://paste.j3ss.co/", "pastebin base uri")
p.FlagSet.StringVar(&baseuri, "uri", "https://paste.j3ss.co/", "pastebin base uri")
p.FlagSet.StringVar(&username, "u", os.Getenv("PASTEBINIT_USERNAME"), "username (or env var PASTEBINIT_USERNAME)")
p.FlagSet.StringVar(&username, "username", os.Getenv("PASTEBINIT_USERNAME"), "username (or env var PASTEBINIT_USERNAME)")
p.FlagSet.StringVar(&password, "p", os.Getenv("PASTEBINIT_PASSWORD"), "password (or env var PASTEBINIT_PASSWORD)")
p.FlagSet.StringVar(&password, "password", os.Getenv("PASTEBINIT_PASSWORD"), "password (or env var PASTEBINIT_PASSWORD)")
p.FlagSet.BoolVar(&debug, "d", false, "enable debug logging")
p.FlagSet.BoolVar(&debug, "debug", false, "enable debug logging")
// Set the before function.
p.Before = func(ctx context.Context) error {
// On ^C, or SIGTERM handle exit.
signals := make(chan os.Signal)
signal.Notify(signals, os.Interrupt)
signal.Notify(signals, syscall.SIGTERM)
_, cancel := context.WithCancel(ctx)
go func() {
for sig := range signals {
cancel()
logrus.Infof("Received %s, exiting.", sig.String())
os.Exit(0)
}
}()
// Set the log level.
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
// make sure uri ends with trailing /
if !strings.HasSuffix(baseuri, "/") {
baseuri += "/"
}
// make sure it starts with http(s)://
if !strings.HasPrefix(baseuri, "http") {
baseuri = "http://" + baseuri
}
// make sure we have a username and password
if len(username) < 1 {
return errors.New("username cannot be empty")
}
if len(password) < 1 {
return errors.New("password cannot be empty")
}
return nil
}
p.Action = func(ctx context.Context, args []string) error {
// check if we are reading from a file or stdin
var content []byte
if len(args) == 0 {
content = readFromStdin()
} else {
filename := args[0]
content = readFromFile(filename)
}
pasteURI, err := postPaste(content)
if err != nil {
return err
}
fmt.Printf("Your paste has been uploaded here:\n%s\nthe raw object is here: %s/raw", pasteURI, pasteURI)
return nil
}
// Run our program.
p.Run()
}
// readFromStdin returns everything in stdin.
func readFromStdin() []byte {
stdin, err := ioutil.ReadAll(os.Stdin)
if err != nil {
logrus.Fatalf("reading from stdin failed: %v", err)
}
return stdin
}
// readFromFile returns the contents of a file.
func readFromFile(filename string) []byte {
if _, err := os.Stat(filename); os.IsNotExist(err) {
logrus.Fatalf("No such file or directory: %q", filename)
}
file, err := ioutil.ReadFile(filename)
if err != nil {
logrus.Fatalf("reading from file %q failed: %v", filename, err)
}
return file
}
// postPaste uploads the paste content to the server
// and returns the paste URI.
func postPaste(content []byte) (string, error) {
// create the request
req, err := http.NewRequest("POST", baseuri+"paste", bytes.NewBuffer(content))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(username, password)
// do the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("request to %spaste failed: %v", baseuri, err)
}
defer resp.Body.Close()
if resp.StatusCode == 401 {
return "", fmt.Errorf("unauthorized - please check your username and password: %d", resp.StatusCode)
}
if resp.StatusCode == 413 {
return "", fmt.Errorf("%d: Payload Too Large. Make sure your proxy or load balancer allows request bodies as large as any file you wish to accept", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("reading response body failed: %v", err)
}
var response map[string]string
if err = json.Unmarshal(body, &response); err != nil {
return "", fmt.Errorf("parsing body as json failed: %v", err)
}
if respError, ok := response["error"]; ok {
return "", fmt.Errorf("server responded with %s", respError)
}
pasteURI, ok := response["uri"]
if !ok {
return "", fmt.Errorf("what the hell did we get back even? %s", string(body))
}
return pasteURI, nil
}