git.iko.soy/typeable/oauth2-proxy
on d64d717 help sign in
72 lines 2.7 kB history raw
1package upstream
3import (
4 "fmt"
5 "net/http"
6 "net/url"
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
12// ProxyErrorHandler is a function that will be used to render error pages when
13// HTTP proxies fail to connect to upstream servers.
14type ProxyErrorHandler func(http.ResponseWriter, *http.Request, error)
16// NewProxy creates a new multiUpstreamProxy that can serve requests directed to
17// multiple upstreams.
18func NewProxy(upstreams options.Upstreams, sigData *options.SignatureData, errorHandler ProxyErrorHandler) (http.Handler, error) {
19 m := &multiUpstreamProxy{
20 serveMux: http.NewServeMux(),
21 }
23 for _, upstream := range upstreams {
24 if upstream.Static {
25 m.registerStaticResponseHandler(upstream)
26 continue
27 }
29 u, err := url.Parse(upstream.URI)
30 if err != nil {
31 return nil, fmt.Errorf("error parsing URI for upstream %q: %w", upstream.ID, err)
32 }
33 switch u.Scheme {
34 case fileScheme:
35 m.registerFileServer(upstream, u)
36 case httpScheme, httpsScheme:
37 m.registerHTTPUpstreamProxy(upstream, u, sigData, errorHandler)
38 default:
39 return nil, fmt.Errorf("unknown scheme for upstream %q: %q", upstream.ID, u.Scheme)
40 }
41 }
42 return m, nil
45// multiUpstreamProxy will serve requests directed to multiple upstream servers
46// registered in the serverMux.
47type multiUpstreamProxy struct {
48 serveMux *http.ServeMux
51// ServerHTTP handles HTTP requests.
52func (m *multiUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
53 m.serveMux.ServeHTTP(rw, req)
56// registerStaticResponseHandler registers a static response handler with at the given path.
57func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upstream) {
58 logger.Printf("mapping path %q => static response %d", upstream.Path, derefStaticCode(upstream.StaticCode))
59 m.serveMux.Handle(upstream.Path, newStaticResponseHandler(upstream.ID, upstream.StaticCode))
62// registerFileServer registers a new fileServer based on the configuration given.
63func (m *multiUpstreamProxy) registerFileServer(upstream options.Upstream, u *url.URL) {
64 logger.Printf("mapping path %q => file system %q", upstream.Path, u.Path)
65 m.serveMux.Handle(upstream.Path, newFileServer(upstream.ID, upstream.Path, u.Path))
68// registerHTTPUpstreamProxy registers a new httpUpstreamProxy based on the configuration given.
69func (m *multiUpstreamProxy) registerHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *options.SignatureData, errorHandler ProxyErrorHandler) {
70 logger.Printf("mapping path %q => upstream %q", upstream.Path, upstream.URI)
71 m.serveMux.Handle(upstream.Path, newHTTPUpstreamProxy(upstream, u, sigData, errorHandler))