forked from PierreZ/goStatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomHeaders.go
106 lines (85 loc) · 2.59 KB
/
customHeaders.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
105
106
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
// HeaderConfigArray is the array which contains all the custom header rules
type HeaderConfigArray struct {
Configs []HeaderConfig `json:"configs"`
}
// HeaderConfig is a single header rule specification
type HeaderConfig struct {
Path string `json:"path"`
FileExtension string `json:"fileExtension"`
Headers []HeaderDefiniton `json:"headers"`
}
// HeaderDefiniton is a key value pair of a specified header rule
type HeaderDefiniton struct {
Key string `json:"key"`
Value string `json:"value"`
}
var headerConfigs HeaderConfigArray
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func logHeaderConfig(config HeaderConfig) {
fmt.Println("Path: " + config.Path)
fmt.Println("FileExtension: " + config.FileExtension)
for j := 0; j < len(config.Headers); j++ {
headerRule := config.Headers[j]
fmt.Println(headerRule.Key, ":", headerRule.Value)
}
fmt.Println("------------------------------")
}
func initHeaderConfig(headerConfigPath string) bool {
headerConfigValid := false
if fileExists(headerConfigPath) {
jsonFile, err := os.Open(headerConfigPath)
if err != nil {
fmt.Println("Cant't read header config file. Error:")
fmt.Println(err)
} else {
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &headerConfigs)
if len(headerConfigs.Configs) > 0 {
headerConfigValid = true
fmt.Println("Found header config file. Rules:")
fmt.Println("------------------------------")
for i := 0; i < len(headerConfigs.Configs); i++ {
configEntry := headerConfigs.Configs[i]
logHeaderConfig(configEntry)
}
} else {
fmt.Println("No rules found in header config file.")
}
}
jsonFile.Close()
}
return headerConfigValid
}
func customHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqFileExtension := filepath.Ext(r.URL.Path)
for i := 0; i < len(headerConfigs.Configs); i++ {
configEntry := headerConfigs.Configs[i]
fileMatch := configEntry.FileExtension == "*" || reqFileExtension == "."+configEntry.FileExtension
pathMatch := configEntry.Path == "*" || strings.HasPrefix(r.URL.Path, configEntry.Path)
if fileMatch && pathMatch {
for j := 0; j < len(configEntry.Headers); j++ {
headerEntry := configEntry.Headers[j]
w.Header().Set(headerEntry.Key, headerEntry.Value)
}
}
}
next.ServeHTTP(w, r)
})
}