aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/handlers/fs.go
blob: 96f11d015aae417898757da07836dafc561b7da0 (plain)
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
package handlers

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

type fsContext struct {
	err			*log.Logger
	path		string
	contentType	string
}

func (ctx *fsContext) readdir(w http.ResponseWriter, r *http.Request) {
	entries, err := os.ReadDir(ctx.path)
	if err != nil {
		ctx.err.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
		return
	}

	files := make([]string, len(entries))
	for index, value := range entries {
		files[index] = value.Name()
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(files)
}

func (ctx *fsContext) get(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("file")

	file, err := os.ReadFile(ctx.path + "/" + name)
	if err != nil {
		ctx.err.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
		return
	}

	if ctx.contentType != "" {
		w.Header().Set("Content-Type", ctx.contentType)
	} else {
		switch filepath.Ext(name) {
			case ".css":
				w.Header().Set("Content-Type", "text/css")
			case ".js":
				w.Header().Set("Content-Type", "text/javascript")
			case ".svg":
				w.Header().Set("Content-Type", "image/svg+xml")
			case ".png":
				w.Header().Set("Content-Type", "image/png")
		}
	}

	w.Write(file)
}