-
Notifications
You must be signed in to change notification settings - Fork 1
/
godown.go
318 lines (293 loc) · 8.24 KB
/
godown.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"github.com/davinche/godown/coordinator"
"github.com/urfave/cli"
)
var port int
var browser string
var shouldLaunch bool
var logging string
var VERSION string
func main() {
// ------------------------------------------------------------------------
// Flags ------------------------------------------------------------------
// ------------------------------------------------------------------------
app := cli.NewApp()
app.Name = "godown"
app.Usage = "A markdown previewer written in Go"
app.Version = VERSION
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p",
Value: 1337,
Usage: "the port for the markdown server",
Destination: &port,
},
cli.StringFlag{
Name: "browser, b",
Value: "",
Usage: "the browser to launch the markdown preview in",
Destination: &browser,
},
cli.BoolFlag{
Name: "l",
Usage: "specify to launch automatically in the browser",
Destination: &shouldLaunch,
},
cli.StringFlag{
Name: "logging",
Usage: "specify logging output (stdout, stderr)",
Value: "",
Destination: &logging,
},
}
// ------------------------------------------------------------------------
// Commands ---------------------------------------------------------------
// ------------------------------------------------------------------------
app.Commands = []cli.Command{
{
Name: "start",
Usage: "preview a file at a given path",
ArgsUsage: "<FILEPATH>",
Action: start,
},
{
Name: "stop",
Usage: "stops the markdown server",
ArgsUsage: "<FILEPATH>",
Action: stop,
},
{
Name: "send",
Usage: "sends data from stdin to the markdown server",
ArgsUsage: "<ID>",
Action: send,
},
}
// See what kind of logging to do
app.Before = func(c *cli.Context) error {
switch strings.ToLower(logging) {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
log.SetOutput(os.Stderr)
default:
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
}
return nil
}
app.Run(os.Args)
}
// ----------------------------------------------------------------------------
// Commands -------------------------------------------------------------------
// ----------------------------------------------------------------------------
func start(c *cli.Context) (ret error) {
ret = nil
file := c.Args().First()
// Make sure a file to load is specified
if file == "" {
cli.ShowSubcommandHelp(c)
return
}
log.Printf("start command: port=%d; shouldLaunch=%v, browser=%q; file=%q",
port, shouldLaunch, browser, file)
// See if we need to start the daemon
coordinator, err := coordinator.New(port)
if err == nil {
// start the daemon
go coordinator.Serve()
addFile(file)
if shouldLaunch {
uniqueID := coordinator.GetID(file)
if uniqueID != "" {
launchBrowser(uniqueID)
} else {
log.Println("error: could not get uniqueID to launch browser")
}
}
coordinator.Wait()
return
}
log.Printf("error: could not start coordinator: will try to POST: err=%q\n", err)
addFile(file)
if shouldLaunch {
uniqueID := getID(file)
if uniqueID != "" {
launchBrowser(uniqueID)
}
}
return
}
func stop(c *cli.Context) (ret error) {
ret = nil
file := c.Args().First()
log.Printf("stop command: port=%d; file=%q\n", port, file)
if file == "" {
killServer()
return
}
killFile(file)
return
}
func send(c *cli.Context) (ret error) {
ret = nil
file := c.Args().First()
// Make sure an identifier is sent
if file == "" {
cli.ShowSubcommandHelp(c)
return
}
log.Printf("send command: port=%d; shouldLaunch=%v\n", port, shouldLaunch)
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("error: could not read markdown data: error=%q\n", err)
}
log.Printf("send command: read data: data=%q\n", string(data))
// See if we need to start the daemon
coordinator, err := coordinator.New(port)
if err == nil {
// start the daemon
go coordinator.Serve()
addData(file, data)
if shouldLaunch {
fmt.Println("FILE")
fmt.Println(file)
uniqueID := coordinator.GetID(file)
fmt.Println("UNIQUEID")
fmt.Println(uniqueID)
if uniqueID != "" {
launchBrowser(uniqueID)
} else {
log.Println("error: could not get uniqueID to launch browser")
}
}
coordinator.Wait()
return
}
addData(file, data)
if shouldLaunch {
uniqueID := getID(file)
if uniqueID != "" {
launchBrowser(uniqueID)
}
}
return
}
// ----------------------------------------------------------------------------
// Launch Browser Helper-------------------------------------------------------
// ----------------------------------------------------------------------------
func launchBrowser(id string) {
// Launch the browser
var args []string
if browser == "" {
switch runtime.GOOS {
case "darwin":
args = append(args, "open", "-g")
break
case "linux":
args = append(args, "xdg-open")
break
case "windows":
args = append(args, "cmd", "/C", "start", "/B")
break
}
} else {
args = append(args, browser)
}
if len(args) == 0 {
log.Println("error: could not determine how to launch browser")
}
args = append(args, "http://localhost:"+strconv.Itoa(port)+"?id="+id)
log.Printf("launch browser cmd: args=%v\n", args)
command := exec.Command(args[0], args[1:]...)
err := command.Start()
if err != nil {
log.Printf("error: could not launch browser: %v\n", err)
}
}
// ----------------------------------------------------------------------------
// HTTP API Helpers -----------------------------------------------------------
// ----------------------------------------------------------------------------
func addFile(filePath string) {
client := http.Client{}
marshalled, err := json.Marshal(&struct{ Path string }{filePath})
if err != nil {
log.Fatalf("error: could not marshal filePath: error=%q\n", err)
}
req, err := http.NewRequest("POST", "http://localhost:"+strconv.Itoa(port), bytes.NewBuffer(marshalled))
if err != nil {
log.Fatalf("error: could create http request: error=%q\n", err)
}
res, err := client.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
log.Fatalf("error: could not preview markdown file: err=%q; statusCode=%q\n", err, res.StatusCode)
}
}
func getID(filePath string) string {
client := http.Client{}
req, err := http.NewRequest("GET", "http://localhost:"+strconv.Itoa(port)+"/getid?path="+filePath, nil)
if err != nil {
log.Fatalf("error: could create http getID request: error=%q\n", err)
}
res, err := client.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
log.Fatalf("error: could not get ID of the file: err=%q; statusCode=%q\n", err, res.StatusCode)
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("error: could not get ID of the file from body: err=%q\n")
}
return string(data)
}
func addData(id string, data []byte) {
fmt.Println("in ADD DAata")
fmt.Println(id)
client := http.Client{}
req, err := http.NewRequest(
"PUT",
"http://localhost:"+strconv.Itoa(port)+"?id="+id,
bytes.NewBuffer(data),
)
if err != nil {
log.Fatalf("error: could not create PUT request: error=%q\n", err)
}
res, err := client.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
log.Fatalf("error: could not send data to markdown server: error=%q; statusCode=%q\n", err, res.StatusCode)
}
}
func killServer() {
client := http.Client{}
req, err := http.NewRequest("DELETE", "http://localhost:"+strconv.Itoa(port), nil)
if err != nil {
log.Fatalf("error: could not create shutdown request: error=%q\n", err)
}
res, err := client.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
log.Fatalf("error: could not shutdown server: error=%q; statusCode=%q\n", err, res.StatusCode)
}
}
func killFile(file string) {
client := http.Client{}
req, err := http.NewRequest("DELETE", "http://localhost:"+strconv.Itoa(port)+"?id="+file, nil)
if err != nil {
log.Fatalf("error: could not create delete file request: error=%q\n", err)
}
res, err := client.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
log.Fatalf("error: could not delete file: error=%q; statusCode=%q\n", err, res.StatusCode)
}
}