aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/header_merger.go
blob: 706ca290a53f8e5f6abdcddc48113b8e60a22a02 (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
package middleware

import (
	"strings"

	"github.com/labstack/echo/v4"
)

func mergeHeaders(c echo.Context) {
	hdr := c.Response().Header()

	// echo duplicates the Vary header a few places so deduplicate them and
	// write it out as a comma separated list instead of as many duplicate
	// headers.
	if vh := hdr.Values(echo.HeaderVary); len(vh) > 1 {
		seen := map[string]bool{}
		out := []string{}
		for _, v := range vh {
			if _, ok := seen[v]; !ok {
				seen[v] = true
				out = append(out, v)
			}
		}
		hdr.Set(echo.HeaderVary, strings.Join(out, ", "))
	}
}

// MergeHeaders merges together specific sets of duplicated headers. It
// doesn't try to be a general solution to header duplication because
// that would be too error prone. Currently this only works for the Vary
// header.
func MergeHeaders() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			c.Response().Before(func() { mergeHeaders(c) })
			return next(c)
		}
	}
}