Welcome to mirror list, hosted at ThFree Co, Russian Federation.

middleware.go « routing « internal - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1b15f55c76b0bb547a55de4432b841a0f8b8db10 (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
40
41
42
43
package routing

import (
	"context"
	"errors"
	"net/http"

	"gitlab.com/gitlab-org/gitlab-pages/internal/domain"
	"gitlab.com/gitlab-org/gitlab-pages/internal/httperrors"
	"gitlab.com/gitlab-org/gitlab-pages/internal/logging"
	"gitlab.com/gitlab-org/gitlab-pages/internal/request"
	"gitlab.com/gitlab-org/gitlab-pages/internal/source"
)

// NewMiddleware returns middleware which determine the host and domain for the request, for
// downstream middlewares to use
func NewMiddleware(handler http.Handler, s source.Source) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// if we could not retrieve a domain from domains source we break the
		// middleware chain and simply respond with 502 after logging this
		d, err := getDomain(r, s)
		if err != nil && !errors.Is(err, domain.ErrDomainDoesNotExist) {
			if errors.Is(err, context.Canceled) {
				httperrors.Serve404(w)
				return
			}

			logging.LogRequest(r).WithError(err).Error("could not fetch domain information from a source")

			httperrors.Serve502(w)
			return
		}

		r = domain.ReqWithDomain(r, d)

		handler.ServeHTTP(w, r)
	})
}

func getDomain(r *http.Request, s source.Source) (*domain.Domain, error) {
	host := request.GetHostWithoutPort(r)
	return s.GetDomain(r.Context(), host)
}