-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
78 lines (66 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
78
package main
import (
"errors"
"io/fs"
"log"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"strings"
)
var Mimetypes = map[string]bool{".png": true, ".jpg": true, ".jpeg": true}
var images []string
func main() {
const p = "."
images = findInPath(p)
indexHandler := func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/cats/"+getRandomCat(), 321)
}
http.HandleFunc("/", indexHandler)
fileServer := http.FileServer(imgDir(p))
http.Handle("/cats/", http.StripPrefix("/cats/", fileServer))
catHandler := func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
http.ServeFile(w, req, getRandomCat())
}
http.HandleFunc("/cat", catHandler)
iconHandler := func(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, "./favicon.svg")
}
http.HandleFunc("/favicon.ico", iconHandler)
log.Fatal(http.ListenAndServe(":8090", nil))
}
type imgDir string
func (d imgDir) Open(name string) (http.File, error) {
if !Mimetypes[strings.ToLower(filepath.Ext(name))] {
return nil, errors.New("not image")
}
if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
return nil, errors.New("invalid character in file path")
}
dir := string(d)
fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
f, err := os.Open(fullName)
if err != nil {
return nil, err
}
return f, nil
}
func findInPath(path string) []string {
var a []string
filepath.WalkDir(path, func(s string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
if Mimetypes[filepath.Ext(d.Name())] {
a = append(a, s)
}
return nil
})
return a
}
func getRandomCat() string {
return images[rand.Intn(len(images)-0)+0]
}