/
main.go
95 lines (74 loc) · 2.04 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
package main
import (
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"log"
"net/http"
"os"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/enaeseth/asciist/client"
"github.com/enaeseth/asciist/convert"
"github.com/enaeseth/asciist/service"
)
var (
app = kingpin.New("asciist", "ASCII art as a service")
cli = app.Command("convert", "Convert an image using the service")
clientURL = cli.Flag("url", "URL of the service").Short('u').Default("http://localhost:27244").String()
clientWidth = cli.Flag("width", "Character width to output").Short('w').Uint()
clientFile = cli.Arg("file", "Input image file").File()
serve = app.Command("serve", "Run the service")
debug = serve.Flag("debug", "Use debugging mode").Bool()
host = serve.Flag("host", "Interface to listen on").Envar("HOST").String()
port = serve.Flag("port", "Port to listen on").Default("27244").Envar("PORT").Int()
test = app.Command("test", "Convert an image locally")
testWidth = test.Flag("width", "Character width to output").Short('w').Uint()
testFile = test.Arg("file", "Input image file").File()
)
func main() {
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
case cli.FullCommand():
runClient()
case serve.FullCommand():
runService()
case test.FullCommand():
runLocal()
}
}
func runClient() {
c := client.New(*clientURL)
art, err := c.Convert(readInput(clientFile), width(clientWidth))
if err != nil {
log.Fatal(err)
}
fmt.Println(art)
}
func runService() {
service.SetDebug(*debug)
listen := fmt.Sprintf("%s:%d", *host, *port)
s := service.New()
fmt.Printf("Listening on %s\n", listen)
http.ListenAndServe(listen, s)
}
func runLocal() {
img, _, err := image.Decode(readInput(testFile))
if err != nil {
log.Fatal(err)
}
art := convert.FromImage(img, width(testWidth))
fmt.Println(art)
}
func readInput(fileArg **os.File) *os.File {
if *fileArg != nil {
return *fileArg
}
return os.Stdin
}
func width(widthArg *uint) uint {
if widthArg != nil && *widthArg != 0 {
return *widthArg
}
return defaultWidth()
}