-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
73 lines (61 loc) · 1.78 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
package main
import (
"fmt"
"github.com/proudlygeek/goscii/encoder"
"github.com/proudlygeek/goscii/mongodb/manager"
"html/template"
"log"
"net/http"
"os"
)
var (
asciiEncoder = &encoder.Encoder{}
mongoArtManager = &manager.MongoArtManager{Encoder: asciiEncoder, DatabaseURL: os.Getenv("MONGOLAB_URI")}
)
func logException(res http.ResponseWriter, req *http.Request) {
str := recover()
fmt.Println("[ERROR]:", str)
http.Redirect(res, req, "/", 302)
}
func home(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/html")
t, _ := template.ParseFiles("templates/layout.html", "templates/index.html")
t.Execute(res, nil)
}
func upload(res http.ResponseWriter, req *http.Request) {
defer logException(res, req)
if req.Method == "POST" {
file, _, err := req.FormFile("pic")
if err != nil {
log.Panic(err)
}
defer file.Close()
wr := &manager.MongoWriter{}
image, err := asciiEncoder.DecodeImage(file)
if err != nil {
log.Panic(err)
}
err = asciiEncoder.Asciify(image, wr)
if err != nil {
log.Panic(err)
}
uri := mongoArtManager.Save(wr)
http.Redirect(res, req, "/art/"+uri, 302)
}
}
func show(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/html")
t, _ := template.ParseFiles("templates/layout.html", "templates/upload.html")
t.Execute(res, nil)
fmt.Println("Loading Art", req.URL.Path[5:])
art := mongoArtManager.Load(req.URL.Path[5:])
fmt.Fprintf(res, "%s", art)
}
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
http.HandleFunc("/", home)
http.HandleFunc("/art/", show)
http.HandleFunc("/upload", upload)
fmt.Println("Running on 127.0.0.1:", os.Getenv("PORT"))
http.ListenAndServe("0.0.0.0:"+os.Getenv("PORT"), nil)
}