-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
77 lines (67 loc) · 1.7 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
package main
import (
"encoding/base64"
"fmt"
"html/template"
"log"
"net/http"
"time"
)
const version = "0.0.1"
const templateDir = "templates/*"
// Must be able to compile all template files.
var templates = template.Must(template.ParseGlob(templateDir))
func main() {
http.HandleFunc("/", HomeHandler) // Load main page
http.HandleFunc("/resources/", includeHandler) // Loads css/js/etc. straight through.
srv := &http.Server{
Addr: ":443",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
}
type Page struct {
Pt string // Plaintext
En string // Encoded
}
// Handle all requests for home page, including POST.
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%q\n", r)
if r.Method != "POST" {
renderIndex(w, &Page{})
} else {
plaintext := r.PostFormValue("plaintext")
if plaintext == "" {
encoded := r.PostFormValue("encoded")
if encoded == "" {
renderIndex(w, &Page{})
} else {
page := &Page{}
temp, err := base64.StdEncoding.DecodeString(encoded)
page.Pt = string(temp)
if err != nil {
page.Pt = err.Error()
}
renderIndex(w, page)
}
} else {
page := &Page{}
page.En = base64.StdEncoding.EncodeToString([]byte(plaintext))
renderIndex(w, page)
}
}
}
// Render just the home page.
func renderIndex(w http.ResponseWriter, p *Page) {
err := templates.ExecuteTemplate(w, "main", p)
if err != nil {
panic(err.Error())
}
}
// For resource files like js, images, etc.
// Just a straight through file server.
func includeHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Path[1:]
http.ServeFile(w, r, filename)
}