-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #39 from phartenfeller/master
Middleware to configure response headers
- Loading branch information
Showing
4 changed files
with
202 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
# Header Config | ||
|
||
With the header config, you can specify custom [HTTP Header](https://developer.mozilla.org/de/docs/Web/HTTP/Headers) for the responses of certain file types and paths. | ||
|
||
## Config | ||
|
||
You have to create a JSON file that serves as a config. The JSON must contain a `configs` array. For every entry, you can specify a certain path that must be matched as well as a file extension. You can use the `*` symbol to use the config entry for any path or filename. Note that the path option only matches the requested path from the start. Thatswhy you have to start with a `/` and can use paths like `/files/static/css`. The `headers` array includes a key-value pair of the actual header rule. The headers are not parsed so double check your spelling and test your site. | ||
|
||
The created JSON config has to be mounted into the container via a volume into `/config/headerConfig.json` per default. When this file does not exist inside the container, the header middleware will not be active. | ||
|
||
Example command to add to the docker run command: | ||
|
||
``` | ||
docker run ... -v /your/path/to/the/config/myConfig.json:/config/headerConfig.json | ||
``` | ||
|
||
You can also specify where you want to mount your config into with the `header-config-path` flag: | ||
|
||
``` | ||
docker run ... -v /your/path/to/the/config/myConfig.json:/other/path/myConfig.json -header-config-path=/other/path/myConfig.json | ||
``` | ||
|
||
On startup, the container will log the found header rules. | ||
|
||
## Example headerConfig.json | ||
|
||
```json | ||
{ | ||
"configs": [ | ||
{ | ||
"path": "*", | ||
"fileExtension": "html", | ||
"headers": [ | ||
{ | ||
"key": "cache-control", | ||
"value": "public, max-age=0, must-revalidate" | ||
}, | ||
{ | ||
"key": "Strict-Transport-Security", | ||
"value": "max-age=31536000; includeSubDomains;" | ||
} | ||
] | ||
}, | ||
{ | ||
"path": "*", | ||
"fileExtension": "css", | ||
"headers": [ | ||
{ | ||
"key": "cache-control", | ||
"value": "public, max-age=31536000, immutable" | ||
} | ||
] | ||
}, | ||
{ | ||
"path": "/page-data", | ||
"fileExtension": "json", | ||
"headers": [ | ||
{ | ||
"key": "cache-control", | ||
"value": "public, max-age=0, must-revalidate" | ||
}, | ||
{ | ||
"key": "content-language", | ||
"value": "en" | ||
} | ||
] | ||
}, | ||
{ | ||
"path": "/static/", | ||
"fileExtension": "*", | ||
"headers": [ | ||
{ | ||
"key": "cache-control", | ||
"value": "public, max-age=31536000, immutable" | ||
} | ||
] | ||
} | ||
] | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters