-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
main.go
104 lines (93 loc) · 2.56 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
package main
import (
"crypto/sha1"
"encoding/json"
"fmt"
"github.com/gorilla/context"
"github.com/gorilla/sessions"
"html/template"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
var tpl *template.Template
var store = sessions.NewCookieStore([]byte("secret-password"))
func init() {
tpl, _ = template.ParseGlob("assets/templates/*.html")
}
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
http.Handle("/assets/imgs/", http.StripPrefix("/assets/imgs", http.FileServer(http.Dir("./assets/imgs"))))
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
}
func index(res http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "session")
// authenticate
if session.Values["loggedin"] == "false" || session.Values["loggedin"] == nil {
http.Redirect(res, req, "/login", 302)
return
}
// upload photo
src, hdr, err := req.FormFile("data")
if req.Method == "POST" && err == nil {
uploadPhoto(src, hdr, session)
}
// save session
session.Save(req, res)
// get photos
data := getPhotos(session)
// execute template
tpl.ExecuteTemplate(res, "index.html", data)
}
func logout(res http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "session")
session.Values["loggedin"] = "false"
session.Save(req, res)
http.Redirect(res, req, "/login", 302)
}
func login(res http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "session")
if req.Method == "POST" && req.FormValue("password") == "secret" {
session.Values["loggedin"] = "true"
session.Save(req, res)
http.Redirect(res, req, "/", 302)
return
}
// execute template
tpl.ExecuteTemplate(res, "login.html", nil)
}
func uploadPhoto(src multipart.File, hdr *multipart.FileHeader, session *sessions.Session) {
defer src.Close()
fName := getSha(src) + ".jpg"
wd, _ := os.Getwd()
path := filepath.Join(wd, "assets", "imgs", fName)
dst, _ := os.Create(path)
defer dst.Close()
src.Seek(0, 0)
io.Copy(dst, src)
addPhoto(fName, session)
}
func getSha(src multipart.File) string {
h := sha1.New()
io.Copy(h, src)
return fmt.Sprintf("%x", h.Sum(nil))
}
func addPhoto(fName string, session *sessions.Session) {
data := getPhotos(session)
data = append(data, fName)
bs, _ := json.Marshal(data)
session.Values["data"] = string(bs)
}
func getPhotos(session *sessions.Session) []string {
var data []string
jsonData := session.Values["data"]
if jsonData != nil {
json.Unmarshal([]byte(jsonData.(string)), &data)
}
return data
}