-
Notifications
You must be signed in to change notification settings - Fork 79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Middleware to configure response headers #39
Merged
+202
−6
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
adb719e
custom header test
phartenfeller 2c00fb0
use json config + changed headers to key value array
phartenfeller 1557fd3
split headerConfig logic to new file and middleware
phartenfeller dbdda5e
custom header documentation
phartenfeller 73eac2e
improved found rules logging
phartenfeller 64bc411
updated readme
phartenfeller 3438532
Config path can be specified with a parameter
phartenfeller File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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() bool { | ||
headerConfigValid := false | ||
|
||
if fileExists("/config/headerConfig.json") { | ||
jsonFile, err := os.Open("/config/headerConfig.json") | ||
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,74 @@ | ||
# 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`. 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: | ||
|
||
``` | ||
-v /your/path/to/the/config/myConfig.json:/config/headerConfig.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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can the path be a parameter from cli with this default?