Skip to content
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
merged 7 commits into from
Sep 29, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Yeah, decided to drop support of unsecured HTTPS. Two-years ago, when I started
* Light container
* More secure than official images (see below)
* Log enabled
* Specify custom response headers per path and filetype [(info)](./docs/header-config.md)

### Why?
Because the official Golang image is wayyyy too big (around 1/2Gb as you can see below) and could be insecure.
Expand Down
106 changes: 106 additions & 0 deletions customHeaders.go
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") {
Copy link
Owner

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?

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)
})
}
74 changes: 74 additions & 0 deletions docs/header-config.md
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"
}
]
}
]
}
```
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ func handleReq(h http.Handler) http.Handler {
if *logRequest {
log.Println(r.Method, r.URL.Path)
}

h.ServeHTTP(w, r)
})
}
Expand Down Expand Up @@ -122,6 +123,11 @@ func main() {
handler = authMiddleware(handler)
}

headerConfigValid := initHeaderConfig()
if headerConfigValid {
handler = customHeadersMiddleware(handler)
}

// Extra headers.
if len(*headerFlag) > 0 {
header, headerValue := parseHeaderFlag(*headerFlag)
Expand Down