summaryrefslogtreecommitdiff
path: root/modules/caddyhttp
diff options
context:
space:
mode:
Diffstat (limited to 'modules/caddyhttp')
-rw-r--r--modules/caddyhttp/encode/brotli/brotli.go95
-rw-r--r--modules/caddyhttp/encode/caddyfile.go1
-rw-r--r--modules/caddyhttp/fileserver/caddyfile.go2
-rw-r--r--modules/caddyhttp/httpcache/httpcache.go242
-rw-r--r--modules/caddyhttp/matchers.go2
-rw-r--r--modules/caddyhttp/requestbody/requestbody.go2
-rw-r--r--modules/caddyhttp/reverseproxy/caddyfile.go30
-rw-r--r--modules/caddyhttp/reverseproxy/circuitbreaker.go20
-rw-r--r--modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go24
-rw-r--r--modules/caddyhttp/reverseproxy/hosts.go73
-rw-r--r--modules/caddyhttp/reverseproxy/reverseproxy.go2
-rw-r--r--modules/caddyhttp/server.go7
-rw-r--r--modules/caddyhttp/standard/imports.go2
13 files changed, 115 insertions, 387 deletions
diff --git a/modules/caddyhttp/encode/brotli/brotli.go b/modules/caddyhttp/encode/brotli/brotli.go
deleted file mode 100644
index fababd3..0000000
--- a/modules/caddyhttp/encode/brotli/brotli.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2015 Matthew Holt and The Caddy Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package caddybrotli
-
-import (
- "fmt"
- "strconv"
-
- "github.com/andybalholm/brotli"
- "github.com/caddyserver/caddy/v2"
- "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
- "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode"
-)
-
-func init() {
- caddy.RegisterModule(Brotli{})
-}
-
-// Brotli can create brotli encoders. Note that brotli
-// is not known for great encoding performance, and
-// its use during requests is discouraged; instead,
-// pre-compress the content instead.
-type Brotli struct {
- Quality *int `json:"quality,omitempty"`
-}
-
-// CaddyModule returns the Caddy module information.
-func (Brotli) CaddyModule() caddy.ModuleInfo {
- return caddy.ModuleInfo{
- ID: "http.encoders.brotli",
- New: func() caddy.Module { return new(Brotli) },
- }
-}
-
-// UnmarshalCaddyfile sets up the handler from Caddyfile tokens.
-func (b *Brotli) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
- for d.Next() {
- if !d.NextArg() {
- continue
- }
- qualityStr := d.Val()
- quality, err := strconv.Atoi(qualityStr)
- if err != nil {
- return err
- }
- b.Quality = &quality
- }
- return nil
-}
-
-// Validate validates b's configuration.
-func (b Brotli) Validate() error {
- if b.Quality != nil {
- quality := *b.Quality
- if quality < brotli.BestSpeed {
- return fmt.Errorf("quality too low; must be >= %d", brotli.BestSpeed)
- }
- if quality > brotli.BestCompression {
- return fmt.Errorf("quality too high; must be <= %d", brotli.BestCompression)
- }
- }
- return nil
-}
-
-// AcceptEncoding returns the name of the encoding as
-// used in the Accept-Encoding request headers.
-func (Brotli) AcceptEncoding() string { return "br" }
-
-// NewEncoder returns a new brotli writer.
-func (b Brotli) NewEncoder() encode.Encoder {
- quality := brotli.DefaultCompression
- if b.Quality != nil {
- quality = *b.Quality
- }
- return brotli.NewWriterLevel(nil, quality)
-}
-
-// Interface guards
-var (
- _ encode.Encoding = (*Brotli)(nil)
- _ caddy.Validator = (*Brotli)(nil)
- _ caddyfile.Unmarshaler = (*Brotli)(nil)
-)
diff --git a/modules/caddyhttp/encode/caddyfile.go b/modules/caddyhttp/encode/caddyfile.go
index 629f0e2..9d9646c 100644
--- a/modules/caddyhttp/encode/caddyfile.go
+++ b/modules/caddyhttp/encode/caddyfile.go
@@ -42,7 +42,6 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error)
// encode [<matcher>] <formats...> {
// gzip [<level>]
// zstd
-// brotli [<quality>]
// }
//
// Specifying the formats on the first line will use those formats' defaults.
diff --git a/modules/caddyhttp/fileserver/caddyfile.go b/modules/caddyhttp/fileserver/caddyfile.go
index 67ae4f4..2980436 100644
--- a/modules/caddyhttp/fileserver/caddyfile.go
+++ b/modules/caddyhttp/fileserver/caddyfile.go
@@ -63,7 +63,7 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error)
}
case "index":
fsrv.IndexNames = h.RemainingArgs()
- if len(fsrv.Hide) == 0 {
+ if len(fsrv.IndexNames) == 0 {
return nil, h.ArgErr()
}
case "root":
diff --git a/modules/caddyhttp/httpcache/httpcache.go b/modules/caddyhttp/httpcache/httpcache.go
deleted file mode 100644
index 605a183..0000000
--- a/modules/caddyhttp/httpcache/httpcache.go
+++ /dev/null
@@ -1,242 +0,0 @@
-// Copyright 2015 Matthew Holt and The Caddy Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package httpcache
-
-import (
- "bytes"
- "context"
- "encoding/gob"
- "fmt"
- "io"
- "log"
- "net/http"
- "sync"
-
- "github.com/caddyserver/caddy/v2"
- "github.com/caddyserver/caddy/v2/modules/caddyhttp"
- "github.com/golang/groupcache"
-)
-
-func init() {
- caddy.RegisterModule(Cache{})
-}
-
-// Cache implements a simple distributed cache.
-//
-// NOTE: This module is a work-in-progress. It is
-// not finished and is NOT ready for production use.
-// [We need your help to finish it! Please volunteer
-// in this issue.](https://github.com/caddyserver/caddy/issues/2820)
-// Until it is finished, this module is subject to
-// breaking changes.
-//
-// Caches only GET and HEAD requests. Honors the Cache-Control: no-cache header.
-//
-// Still TODO:
-//
-// - Eviction policies and API
-// - Use single cache per-process
-// - Preserve cache through config reloads
-// - More control over what gets cached
-type Cache struct {
- // The network address of this cache instance; required.
- Self string `json:"self,omitempty"`
-
- // A list of network addresses of cache instances in the group.
- Peers []string `json:"peers,omitempty"`
-
- // Maximum size of the cache, in bytes. Default is 512 MB.
- MaxSize int64 `json:"max_size,omitempty"`
-
- group *groupcache.Group
-}
-
-// CaddyModule returns the Caddy module information.
-func (Cache) CaddyModule() caddy.ModuleInfo {
- return caddy.ModuleInfo{
- ID: "http.handlers.cache",
- New: func() caddy.Module { return new(Cache) },
- }
-}
-
-// Provision provisions c.
-func (c *Cache) Provision(ctx caddy.Context) error {
- // TODO: use UsagePool so that cache survives config reloads - TODO: a single cache for whole process?
- maxSize := c.MaxSize
- if maxSize == 0 {
- const maxMB = 512
- maxSize = int64(maxMB << 20)
- }
- poolMu.Lock()
- if pool == nil {
- pool = groupcache.NewHTTPPool(c.Self)
- c.group = groupcache.NewGroup(groupName, maxSize, groupcache.GetterFunc(c.getter))
- } else {
- c.group = groupcache.GetGroup(groupName)
- }
- pool.Set(append(c.Peers, c.Self)...)
- poolMu.Unlock()
-
- return nil
-}
-
-// Validate validates c.
-func (c *Cache) Validate() error {
- if c.Self == "" {
- return fmt.Errorf("address of this instance (self) is required")
- }
- if c.MaxSize < 0 {
- return fmt.Errorf("size must be greater than 0")
- }
- return nil
-}
-
-func (c *Cache) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
- // TODO: proper RFC implementation of cache control headers...
- if r.Header.Get("Cache-Control") == "no-cache" || (r.Method != "GET" && r.Method != "HEAD") {
- return next.ServeHTTP(w, r)
- }
-
- getterCtx := getterContext{w, r, next}
- ctx := context.WithValue(r.Context(), getterContextCtxKey, getterCtx)
-
- // TODO: rigorous performance testing
-
- // TODO: pretty much everything else to handle the nuances of HTTP caching...
-
- // TODO: groupcache has no explicit cache eviction, so we need to embed
- // all information related to expiring cache entries into the key; right
- // now we just use the request URI as a proof-of-concept
- key := r.RequestURI
-
- var cachedBytes []byte
- err := c.group.Get(ctx, key, groupcache.AllocatingByteSliceSink(&cachedBytes))
- if err == errUncacheable {
- return nil
- }
- if err != nil {
- return err
- }
-
- // the cached bytes consists of two parts: first a
- // gob encoding of the status and header, immediately
- // followed by the raw bytes of the response body
- rdr := bytes.NewReader(cachedBytes)
-
- // read the header and status first
- var hs headerAndStatus
- err = gob.NewDecoder(rdr).Decode(&hs)
- if err != nil {
- return err
- }
-
- // set and write the cached headers
- for k, v := range hs.Header {
- w.Header()[k] = v
- }
- w.WriteHeader(hs.Status)
-
- // write the cached response body
- io.Copy(w, rdr)
-
- return nil
-}
-
-func (c *Cache) getter(ctx context.Context, key string, dest groupcache.Sink) error {
- combo := ctx.Value(getterContextCtxKey).(getterContext)
-
- // the buffer will store the gob-encoded header, then the body
- buf := bufPool.Get().(*bytes.Buffer)
- buf.Reset()
- defer bufPool.Put(buf)
-
- // we need to record the response if we are to cache it; only cache if
- // request is successful (TODO: there's probably much more nuance needed here)
- rr := caddyhttp.NewResponseRecorder(combo.rw, buf, func(status int, header http.Header) bool {
- shouldBuf := status < 300
-
- if shouldBuf {
- // store the header before the body, so we can efficiently
- // and conveniently use a single buffer for both; gob
- // decoder will only read up to end of gob message, and
- // the rest will be the body, which will be written
- // implicitly for us by the recorder
- err := gob.NewEncoder(buf).Encode(headerAndStatus{
- Header: header,
- Status: status,
- })
- if err != nil {
- log.Printf("[ERROR] Encoding headers for cache entry: %v; not caching this request", err)
- return false
- }
- }
-
- return shouldBuf
- })
-
- // execute next handlers in chain
- err := combo.next.ServeHTTP(rr, combo.req)
- if err != nil {
- return err
- }
-
- // if response body was not buffered, response was
- // already written and we are unable to cache
- if !rr.Buffered() {
- return errUncacheable
- }
-
- // add to cache
- dest.SetBytes(buf.Bytes())
-
- return nil
-}
-
-type headerAndStatus struct {
- Header http.Header
- Status int
-}
-
-type getterContext struct {
- rw http.ResponseWriter
- req *http.Request
- next caddyhttp.Handler
-}
-
-var bufPool = sync.Pool{
- New: func() interface{} {
- return new(bytes.Buffer)
- },
-}
-
-var (
- pool *groupcache.HTTPPool
- poolMu sync.Mutex
-)
-
-var errUncacheable = fmt.Errorf("uncacheable")
-
-const groupName = "http_requests"
-
-type ctxKey string
-
-const getterContextCtxKey ctxKey = "getter_context"
-
-// Interface guards
-var (
- _ caddy.Provisioner = (*Cache)(nil)
- _ caddy.Validator = (*Cache)(nil)
- _ caddyhttp.MiddlewareHandler = (*Cache)(nil)
-)
diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go
index 043831f..81fc396 100644
--- a/modules/caddyhttp/matchers.go
+++ b/modules/caddyhttp/matchers.go
@@ -41,7 +41,7 @@ type (
// especially A/AAAA pointed at your server.
//
// Automatic HTTPS can be
- // [customized or disabled](/docs/json/apps/http/servers/automatic_https/).
+ // [customized or disabled](/docs/modules/http#servers/automatic_https).
MatchHost []string
// MatchPath matches requests by the URI's path (case-insensitive). Path
diff --git a/modules/caddyhttp/requestbody/requestbody.go b/modules/caddyhttp/requestbody/requestbody.go
index dcebd8c..76cd274 100644
--- a/modules/caddyhttp/requestbody/requestbody.go
+++ b/modules/caddyhttp/requestbody/requestbody.go
@@ -34,7 +34,7 @@ type RequestBody struct {
// CaddyModule returns the Caddy module information.
func (RequestBody) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
- ID: "http.handlers.request_body", // TODO: better name for this?
+ ID: "http.handlers.request_body",
New: func() caddy.Module { return new(RequestBody) },
}
}
diff --git a/modules/caddyhttp/reverseproxy/caddyfile.go b/modules/caddyhttp/reverseproxy/caddyfile.go
index 9ff9dce..cefb5b6 100644
--- a/modules/caddyhttp/reverseproxy/caddyfile.go
+++ b/modules/caddyhttp/reverseproxy/caddyfile.go
@@ -177,13 +177,36 @@ func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
return net.JoinHostPort(host, port), nil
}
+ // appendUpstream creates an upstream for address and adds
+ // it to the list. If the address starts with "srv+" it is
+ // treated as a SRV-based upstream, and any port will be
+ // dropped.
+ appendUpstream := func(address string) error {
+ isSRV := strings.HasPrefix(address, "srv+")
+ if isSRV {
+ address = strings.TrimPrefix(address, "srv+")
+ }
+ dialAddr, err := upstreamDialAddress(address)
+ if err != nil {
+ return err
+ }
+ if isSRV {
+ if host, _, err := net.SplitHostPort(dialAddr); err == nil {
+ dialAddr = host
+ }
+ h.Upstreams = append(h.Upstreams, &Upstream{LookupSRV: dialAddr})
+ } else {
+ h.Upstreams = append(h.Upstreams, &Upstream{Dial: dialAddr})
+ }
+ return nil
+ }
+
for d.Next() {
for _, up := range d.RemainingArgs() {
- dialAddr, err := upstreamDialAddress(up)
+ err := appendUpstream(up)
if err != nil {
return err
}
- h.Upstreams = append(h.Upstreams, &Upstream{Dial: dialAddr})
}
for d.NextBlock(0) {
@@ -194,11 +217,10 @@ func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
return d.ArgErr()
}
for _, up := range args {
- dialAddr, err := upstreamDialAddress(up)
+ err := appendUpstream(up)
if err != nil {
return err
}
- h.Upstreams = append(h.Upstreams, &Upstream{Dial: dialAddr})
}
case "lb_policy":
diff --git a/modules/caddyhttp/reverseproxy/circuitbreaker.go b/modules/caddyhttp/reverseproxy/circuitbreaker.go
index 00b38a8..830ab43 100644
--- a/modules/caddyhttp/reverseproxy/circuitbreaker.go
+++ b/modules/caddyhttp/reverseproxy/circuitbreaker.go
@@ -24,12 +24,12 @@ import (
)
func init() {
- caddy.RegisterModule(localCircuitBreaker{})
+ caddy.RegisterModule(internalCircuitBreaker{})
}
-// localCircuitBreaker implements circuit breaking functionality
+// internalCircuitBreaker implements circuit breaking functionality
// for requests within this process over a sliding time window.
-type localCircuitBreaker struct {
+type internalCircuitBreaker struct {
tripped int32
cbFactor int32
threshold float64
@@ -39,15 +39,15 @@ type localCircuitBreaker struct {
}
// CaddyModule returns the Caddy module information.
-func (localCircuitBreaker) CaddyModule() caddy.ModuleInfo {
+func (internalCircuitBreaker) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
- ID: "http.reverse_proxy.circuit_breakers.local",
- New: func() caddy.Module { return new(localCircuitBreaker) },
+ ID: "http.reverse_proxy.circuit_breakers.internal",
+ New: func() caddy.Module { return new(internalCircuitBreaker) },
}
}
// Provision sets up a configured circuit breaker.
-func (c *localCircuitBreaker) Provision(ctx caddy.Context) error {
+func (c *internalCircuitBreaker) Provision(ctx caddy.Context) error {
f, ok := typeCB[c.Factor]
if !ok {
return fmt.Errorf("type is not defined")
@@ -77,19 +77,19 @@ func (c *localCircuitBreaker) Provision(ctx caddy.Context) error {
}
// Ok returns whether the circuit breaker is tripped or not.
-func (c *localCircuitBreaker) Ok() bool {
+func (c *internalCircuitBreaker) Ok() bool {
tripped := atomic.LoadInt32(&c.tripped)
return tripped == 0
}
// RecordMetric records a response status code and execution time of a request. This function should be run in a separate goroutine.
-func (c *localCircuitBreaker) RecordMetric(statusCode int, latency time.Duration) {
+func (c *internalCircuitBreaker) RecordMetric(statusCode int, latency time.Duration) {
c.metrics.Record(statusCode, latency)
c.checkAndSet()
}
// Ok checks our metrics to see if we should trip our circuit breaker, or if the fallback duration has completed.
-func (c *localCircuitBreaker) checkAndSet() {
+func (c *internalCircuitBreaker) checkAndSet() {
var isTripped bool
switch c.cbFactor {
diff --git a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
index 9d2dc39..cff6b39 100644
--- a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
+++ b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
@@ -29,6 +29,7 @@ import (
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
"github.com/caddyserver/caddy/v2/modules/caddytls"
+ "go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
)
@@ -66,6 +67,7 @@ type Transport struct {
WriteTimeout caddy.Duration `json:"write_timeout,omitempty"`
serverSoftware string
+ logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
@@ -77,7 +79,8 @@ func (Transport) CaddyModule() caddy.ModuleInfo {
}
// Provision sets up t.
-func (t *Transport) Provision(_ caddy.Context) error {
+func (t *Transport) Provision(ctx caddy.Context) error {
+ t.logger = ctx.Logger(t)
if t.Root == "" {
t.Root = "{http.vars.root}"
}
@@ -110,6 +113,12 @@ func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) {
address = dialInfo.Address
}
+ t.logger.Debug("roundtrip",
+ zap.Object("request", caddyhttp.LoggableHTTPRequest{Request: r}),
+ zap.String("dial", address),
+ zap.Any("env", env), // TODO: this uses reflection I think
+ )
+
fcgiBackend, err := DialContext(ctx, network, address)
if err != nil {
// TODO: wrap in a special error type if the dial failed, so retries can happen if enabled
@@ -164,7 +173,12 @@ func (t Transport) buildEnv(r *http.Request) (map[string]string, error) {
ip = strings.Replace(ip, "[", "", 1)
ip = strings.Replace(ip, "]", "", 1)
- root := repl.ReplaceAll(t.Root, ".")
+ // make sure file root is absolute
+ root, err := filepath.Abs(repl.ReplaceAll(t.Root, "."))
+ if err != nil {
+ return nil, err
+ }
+
fpath := r.URL.Path
// Split path in preparation for env variables.
@@ -173,8 +187,8 @@ func (t Transport) buildEnv(r *http.Request) (map[string]string, error) {
splitPos := t.splitPos(fpath)
// Request has the extension; path was split successfully
- docURI := fpath[:splitPos+len(t.SplitPath)]
- pathInfo := fpath[splitPos+len(t.SplitPath):]
+ docURI := fpath[:splitPos]
+ pathInfo := fpath[splitPos:]
scriptName := fpath
// Strip PATH_INFO from SCRIPT_NAME
@@ -292,7 +306,7 @@ func (t Transport) splitPos(path string) int {
lowerPath := strings.ToLower(path)
for _, split := range t.SplitPath {
if idx := strings.Index(lowerPath, strings.ToLower(split)); idx > -1 {
- return idx
+ return idx + len(split)
}
}
return -1
diff --git a/modules/caddyhttp/reverseproxy/hosts.go b/modules/caddyhttp/reverseproxy/hosts.go
index 602aab2..a7709ee 100644
--- a/modules/caddyhttp/reverseproxy/hosts.go
+++ b/modules/caddyhttp/reverseproxy/hosts.go
@@ -17,6 +17,8 @@ package reverseproxy
import (
"context"
"fmt"
+ "net"
+ "net/http"
"strconv"
"sync/atomic"
@@ -63,10 +65,10 @@ type UpstreamPool []*Upstream
type Upstream struct {
Host `json:"-"`
- // The [network address](/docs/json/apps/http/#servers/listen)
+ // The [network address](/docs/conventions#network-addresses)
// to dial to connect to the upstream. Must represent precisely
// one socket (i.e. no port ranges). A valid network address
- // either has a host and port, or is a unix socket address.
+ // either has a host and port or is a unix socket address.
//
// Placeholders may be used to make the upstream dynamic, but be
// aware of the health check implications of this: a single
@@ -75,6 +77,11 @@ type Upstream struct {
// backends is down. Also be aware of open proxy vulnerabilities.
Dial string `json:"dial,omitempty"`
+ // If DNS SRV records are used for service discovery with this
+ // upstream, specify the DNS name for which to look up SRV
+ // records here, instead of specifying a dial address.
+ LookupSRV string `json:"lookup_srv,omitempty"`
+
// The maximum number of simultaneous requests to allow to
// this upstream. If set, overrides the global passive health
// check UnhealthyRequestCount value.
@@ -118,6 +125,47 @@ func (u *Upstream) Full() bool {
return u.MaxRequests > 0 && u.Host.NumRequests() >= u.MaxRequests
}
+// fillDialInfo returns a filled DialInfo for upstream u, using the request
+// context. If the upstream has a SRV lookup configured, that is done and a
+// returned address is chosen; otherwise, the upstream's regular dial address
+// field is used. Note that the returned value is not a pointer.
+func (u *Upstream) fillDialInfo(r *http.Request) (DialInfo, error) {
+ repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
+ var addr caddy.ParsedAddress
+
+ if u.LookupSRV != "" {
+ // perform DNS lookup for SRV records and choose one
+ srvName := repl.ReplaceAll(u.LookupSRV, "")
+ _, records, err := net.DefaultResolver.LookupSRV(r.Context(), "", "", srvName)
+ if err != nil {
+ return DialInfo{}, err
+ }
+ addr.Network = "tcp"
+ addr.Host = records[0].Target
+ addr.StartPort, addr.EndPort = uint(records[0].Port), uint(records[0].Port)
+ } else {
+ // use provided dial address
+ var err error
+ dial := repl.ReplaceAll(u.Dial, "")
+ addr, err = caddy.ParseNetworkAddress(dial)
+ if err != nil {
+ return DialInfo{}, fmt.Errorf("upstream %s: invalid dial address %s: %v", u.Dial, dial, err)
+ }
+ if numPorts := addr.PortRangeSize(); numPorts != 1 {
+ return DialInfo{}, fmt.Errorf("upstream %s: dial address must represent precisely one socket: %s represents %d",
+ u.Dial, dial, numPorts)
+ }
+ }
+
+ return DialInfo{
+ Upstream: u,
+ Network: addr.Network,
+ Address: addr.JoinHostPort(0),
+ Host: addr.Host,
+ Port: strconv.Itoa(int(addr.StartPort)),
+ }, nil
+}
+
// upstreamHost is the basic, in-memory representation
// of the state of a remote host. It implements the
// Host interface.
@@ -204,27 +252,6 @@ func (di DialInfo) String() string {
return caddy.JoinNetworkAddress(di.Network, di.Host, di.Port)
}
-// fillDialInfo returns a filled DialInfo for the given upstream, using
-// the given Replacer. Note that the returned value is not a pointer.
-func fillDialInfo(upstream *Upstream, repl *caddy.Replacer) (DialInfo, error) {
- dial := repl.ReplaceAll(upstream.Dial, "")
- addr, err := caddy.ParseNetworkAddress(dial)
- if err != nil {
- return DialInfo{}, fmt.Errorf("upstream %s: invalid dial address %s: %v", upstream.Dial, dial, err)
- }
- if numPorts := addr.PortRangeSize(); numPorts != 1 {
- return DialInfo{}, fmt.Errorf("upstream %s: dial address must represent precisely one socket: %s represents %d",
- upstream.Dial, dial, numPorts)
- }
- return DialInfo{
- Upstream: upstream,
- Network: addr.Network,
- Address: addr.JoinHostPort(0),
- Host: addr.Host,
- Port: strconv.Itoa(int(addr.StartPort)),
- }, nil
-}
-
// GetDialInfo gets the upstream dialing info out of the context,
// and returns true if there was a valid value; false otherwise.
func GetDialInfo(ctx context.Context) (DialInfo, bool) {
diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go
index 4837736..918f7a6 100644
--- a/modules/caddyhttp/reverseproxy/reverseproxy.go
+++ b/modules/caddyhttp/reverseproxy/reverseproxy.go
@@ -313,7 +313,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
// the dial address may vary per-request if placeholders are
// used, so perform those replacements here; the resulting
// DialInfo struct should have valid network address syntax
- dialInfo, err := fillDialInfo(upstream, repl)
+ dialInfo, err := upstream.fillDialInfo(r)
if err != nil {
return fmt.Errorf("making dial info: %v", err)
}
diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go
index 461865c..c7780b0 100644
--- a/modules/caddyhttp/server.go
+++ b/modules/caddyhttp/server.go
@@ -172,7 +172,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger := accLog
if s.Logs != nil && s.Logs.LoggerNames != nil {
- logger = logger.Named(s.Logs.LoggerNames[r.Host])
+ if loggerName, ok := s.Logs.LoggerNames[r.Host]; ok {
+ logger = logger.Named(loggerName)
+ } else {
+ // see if there's a default log name to attach to
+ logger = logger.Named(s.Logs.LoggerNames[""])
+ }
}
log := logger.Info
diff --git a/modules/caddyhttp/standard/imports.go b/modules/caddyhttp/standard/imports.go
index 1effb5a..a0ccf6e 100644
--- a/modules/caddyhttp/standard/imports.go
+++ b/modules/caddyhttp/standard/imports.go
@@ -5,12 +5,10 @@ import (
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode"
- _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/brotli"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/gzip"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode/zstd"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
- _ "github.com/caddyserver/caddy/v2/modules/caddyhttp/httpcache"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/requestbody"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
_ "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy/fastcgi"