Skip to main content

đŸˇī¸ Headers

Headers wraps around your current Response and sets all the headers parsed in the headers parameter provided they are not set. If a header was already set by a previous Response, then it will be skipped.

func Cors(configuration CorsConfiguration) there.Middleware {
return func(request there.Request, next there.Response) there.Response {
headers := map[string]string{
header.ResponseAccessControlAllowOrigin: configuration.AccessControlAllowOrigin,
header.ResponseAccessControlAllowMethods: configuration.AccessControlAllowMethods,
header.ResponseAccessControlAllowHeaders: configuration.AccessControlAllowHeaders,
}
if request.Method == there.MethodOptions {
return there.Headers(headers, there.Status(status.OK))
}
return there.Headers(headers, next)
}
}

When this middleware gets called, all the Cors Headers will be set.

func Headers(headers map[string]string, response Response) Response {
return &headerResponse{headers: headers, response: response}
}

type headerResponse struct {
headers map[string]string
response Response
}

func (h headerResponse) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
for key, value := range h.headers {
// Only set the header, if it wasn't set yet
if len(rw.Header().Get(key)) == 0 {
rw.Header().Set(key, value)
}
}
if h.response != nil {
h.response.ServeHTTP(rw, r)
}
}