chore: Bump up to Go 1.19, minimum 1.18 (#4925)

This commit is contained in:
Francis Lavoie 2022-08-02 16:39:09 -04:00 committed by GitHub
parent db1aa5b5bc
commit 141872ed80
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
62 changed files with 244 additions and 625 deletions

View file

@ -19,16 +19,16 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ ubuntu-latest, macos-latest, windows-latest ] os: [ ubuntu-latest, macos-latest, windows-latest ]
go: [ '1.17', '1.18' ] go: [ '1.18', '1.19' ]
include: include:
# Set the minimum Go patch version for the given Go minor # Set the minimum Go patch version for the given Go minor
# Usable via ${{ matrix.GO_SEMVER }} # Usable via ${{ matrix.GO_SEMVER }}
- go: '1.17'
GO_SEMVER: '~1.17.9'
- go: '1.18' - go: '1.18'
GO_SEMVER: '~1.18.1' GO_SEMVER: '~1.18.4'
- go: '1.19'
GO_SEMVER: '~1.19.0'
# Set some variables per OS, usable via ${{ matrix.VAR }} # Set some variables per OS, usable via ${{ matrix.VAR }}
# CADDY_BIN_PATH: the path to the compiled Caddy binary, for artifact publishing # CADDY_BIN_PATH: the path to the compiled Caddy binary, for artifact publishing

View file

@ -16,13 +16,13 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
goos: ['android', 'linux', 'solaris', 'illumos', 'dragonfly', 'freebsd', 'openbsd', 'plan9', 'windows', 'darwin', 'netbsd'] goos: ['android', 'linux', 'solaris', 'illumos', 'dragonfly', 'freebsd', 'openbsd', 'plan9', 'windows', 'darwin', 'netbsd']
go: [ '1.18' ] go: [ '1.19' ]
include: include:
# Set the minimum Go patch version for the given Go minor # Set the minimum Go patch version for the given Go minor
# Usable via ${{ matrix.GO_SEMVER }} # Usable via ${{ matrix.GO_SEMVER }}
- go: '1.18' - go: '1.19'
GO_SEMVER: '~1.18.1' GO_SEMVER: '~1.19.0'
runs-on: ubuntu-latest runs-on: ubuntu-latest
continue-on-error: true continue-on-error: true

View file

@ -22,7 +22,7 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: '~1.17.9' go-version: '~1.18.4'
check-latest: true check-latest: true
- name: golangci-lint - name: golangci-lint

View file

@ -11,13 +11,13 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ ubuntu-latest ] os: [ ubuntu-latest ]
go: [ '1.18' ] go: [ '1.19' ]
include: include:
# Set the minimum Go patch version for the given Go minor # Set the minimum Go patch version for the given Go minor
# Usable via ${{ matrix.GO_SEMVER }} # Usable via ${{ matrix.GO_SEMVER }}
- go: '1.18' - go: '1.19'
GO_SEMVER: '~1.18.1' GO_SEMVER: '~1.19.0'
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}

View file

@ -75,7 +75,7 @@ For other install options, see https://caddyserver.com/docs/install.
Requirements: Requirements:
- [Go 1.17 or newer](https://golang.org/dl/) - [Go 1.18 or newer](https://golang.org/dl/)
### For development ### For development

View file

@ -441,7 +441,7 @@ func manageIdentity(ctx Context, cfg *Config) error {
if err != nil { if err != nil {
return fmt.Errorf("loading identity issuer modules: %s", err) return fmt.Errorf("loading identity issuer modules: %s", err)
} }
for _, issVal := range val.([]interface{}) { for _, issVal := range val.([]any) {
cfg.Admin.Identity.issuers = append(cfg.Admin.Identity.issuers, issVal.(certmagic.Issuer)) cfg.Admin.Identity.issuers = append(cfg.Admin.Identity.issuers, issVal.(certmagic.Issuer))
} }
} }
@ -1034,7 +1034,7 @@ func handleStop(w http.ResponseWriter, r *http.Request) error {
// only a read lock; all others need a write lock). // only a read lock; all others need a write lock).
func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error { func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error {
var err error var err error
var val interface{} var val any
// if there is a request body, decode it into the // if there is a request body, decode it into the
// variable that will be set in the config according // variable that will be set in the config according
@ -1071,16 +1071,16 @@ func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error
parts = parts[:len(parts)-1] parts = parts[:len(parts)-1]
} }
var ptr interface{} = rawCfg var ptr any = rawCfg
traverseLoop: traverseLoop:
for i, part := range parts { for i, part := range parts {
switch v := ptr.(type) { switch v := ptr.(type) {
case map[string]interface{}: case map[string]any:
// if the next part enters a slice, and the slice is our destination, // if the next part enters a slice, and the slice is our destination,
// handle it specially (because appending to the slice copies the slice // handle it specially (because appending to the slice copies the slice
// header, which does not replace the original one like we want) // header, which does not replace the original one like we want)
if arr, ok := v[part].([]interface{}); ok && i == len(parts)-2 { if arr, ok := v[part].([]any); ok && i == len(parts)-2 {
var idx int var idx int
if method != http.MethodPost { if method != http.MethodPost {
idxStr := parts[len(parts)-1] idxStr := parts[len(parts)-1]
@ -1102,7 +1102,7 @@ traverseLoop:
} }
case http.MethodPost: case http.MethodPost:
if ellipses { if ellipses {
valArray, ok := val.([]interface{}) valArray, ok := val.([]any)
if !ok { if !ok {
return fmt.Errorf("final element is not an array") return fmt.Errorf("final element is not an array")
} }
@ -1137,9 +1137,9 @@ traverseLoop:
case http.MethodPost: case http.MethodPost:
// if the part is an existing list, POST appends to // if the part is an existing list, POST appends to
// it, otherwise it just sets or creates the value // it, otherwise it just sets or creates the value
if arr, ok := v[part].([]interface{}); ok { if arr, ok := v[part].([]any); ok {
if ellipses { if ellipses {
valArray, ok := val.([]interface{}) valArray, ok := val.([]any)
if !ok { if !ok {
return fmt.Errorf("final element is not an array") return fmt.Errorf("final element is not an array")
} }
@ -1170,12 +1170,12 @@ traverseLoop:
// might not exist yet; that's OK but we need to make them as // might not exist yet; that's OK but we need to make them as
// we go, while we still have a pointer from the level above // we go, while we still have a pointer from the level above
if v[part] == nil && method == http.MethodPut { if v[part] == nil && method == http.MethodPut {
v[part] = make(map[string]interface{}) v[part] = make(map[string]any)
} }
ptr = v[part] ptr = v[part]
} }
case []interface{}: case []any:
partInt, err := strconv.Atoi(part) partInt, err := strconv.Atoi(part)
if err != nil { if err != nil {
return fmt.Errorf("[/%s] invalid array index '%s': %v", return fmt.Errorf("[/%s] invalid array index '%s': %v",
@ -1197,7 +1197,7 @@ traverseLoop:
// RemoveMetaFields removes meta fields like "@id" from a JSON message // RemoveMetaFields removes meta fields like "@id" from a JSON message
// by using a simple regular expression. (An alternate way to do this // by using a simple regular expression. (An alternate way to do this
// would be to delete them from the raw, map[string]interface{} // would be to delete them from the raw, map[string]any
// representation as they are indexed, then iterate the index we made // representation as they are indexed, then iterate the index we made
// and add them back after encoding as JSON, but this is simpler.) // and add them back after encoding as JSON, but this is simpler.)
func RemoveMetaFields(rawJSON []byte) []byte { func RemoveMetaFields(rawJSON []byte) []byte {
@ -1329,7 +1329,7 @@ const (
) )
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -115,7 +115,7 @@ func TestUnsyncedConfigAccess(t *testing.T) {
} }
// decode the expected config so we can do a convenient DeepEqual // decode the expected config so we can do a convenient DeepEqual
var expectedDecoded interface{} var expectedDecoded any
err = json.Unmarshal([]byte(tc.expect), &expectedDecoded) err = json.Unmarshal([]byte(tc.expect), &expectedDecoded)
if err != nil { if err != nil {
t.Fatalf("Test %d: Unmarshaling expected config: %v", i, err) t.Fatalf("Test %d: Unmarshaling expected config: %v", i, err)

View file

@ -217,7 +217,7 @@ func changeConfig(method, path string, input []byte, ifMatchHeader string, force
// with what caddy is still running; we need to // with what caddy is still running; we need to
// unmarshal it again because it's likely that // unmarshal it again because it's likely that
// pointers deep in our rawCfg map were modified // pointers deep in our rawCfg map were modified
var oldCfg interface{} var oldCfg any
err2 := json.Unmarshal(rawCfgJSON, &oldCfg) err2 := json.Unmarshal(rawCfgJSON, &oldCfg)
if err2 != nil { if err2 != nil {
err = fmt.Errorf("%v; additionally, restoring old config: %v", err, err2) err = fmt.Errorf("%v; additionally, restoring old config: %v", err, err2)
@ -251,9 +251,9 @@ func readConfig(path string, out io.Writer) error {
// "@id" and maps that ID value to the full configPath in the index. // "@id" and maps that ID value to the full configPath in the index.
// This function is NOT safe for concurrent access; obtain a write lock // This function is NOT safe for concurrent access; obtain a write lock
// on currentCtxMu. // on currentCtxMu.
func indexConfigObjects(ptr interface{}, configPath string, index map[string]string) error { func indexConfigObjects(ptr any, configPath string, index map[string]string) error {
switch val := ptr.(type) { switch val := ptr.(type) {
case map[string]interface{}: case map[string]any:
for k, v := range val { for k, v := range val {
if k == idKey { if k == idKey {
switch idVal := v.(type) { switch idVal := v.(type) {
@ -272,7 +272,7 @@ func indexConfigObjects(ptr interface{}, configPath string, index map[string]str
return err return err
} }
} }
case []interface{}: case []any:
// traverse each element of the array recursively // traverse each element of the array recursively
for i := range val { for i := range val {
err := indexConfigObjects(val[i], path.Join(configPath, strconv.Itoa(i)), index) err := indexConfigObjects(val[i], path.Join(configPath, strconv.Itoa(i)), index)
@ -848,7 +848,7 @@ var (
// to maintain parity with the API endpoint and to avoid // to maintain parity with the API endpoint and to avoid
// the special case of having to access/mutate the variable // the special case of having to access/mutate the variable
// directly without traversing into it. // directly without traversing into it.
rawCfg = map[string]interface{}{ rawCfg = map[string]any{
rawConfigKey: nil, rawConfigKey: nil,
} }

View file

@ -29,12 +29,12 @@ type Adapter struct {
} }
// Adapt converts the Caddyfile config in body to Caddy JSON. // Adapt converts the Caddyfile config in body to Caddy JSON.
func (a Adapter) Adapt(body []byte, options map[string]interface{}) ([]byte, []caddyconfig.Warning, error) { func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconfig.Warning, error) {
if a.ServerType == nil { if a.ServerType == nil {
return nil, nil, fmt.Errorf("no server type") return nil, nil, fmt.Errorf("no server type")
} }
if options == nil { if options == nil {
options = make(map[string]interface{}) options = make(map[string]any)
} }
filename, _ := options["filename"].(string) filename, _ := options["filename"].(string)
@ -116,7 +116,7 @@ type ServerType interface {
// (e.g. CLI flags) and creates a Caddy // (e.g. CLI flags) and creates a Caddy
// config, along with any warnings or // config, along with any warnings or
// an error. // an error.
Setup([]ServerBlock, map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error) Setup([]ServerBlock, map[string]any) (*caddy.Config, []caddyconfig.Warning, error)
} }
// UnmarshalModule instantiates a module with the given ID and invokes // UnmarshalModule instantiates a module with the given ID and invokes

View file

@ -217,7 +217,7 @@ func (d *Dispenser) ValRaw() string {
// ScalarVal gets value of the current token, converted to the closest // ScalarVal gets value of the current token, converted to the closest
// scalar type. If there is no token loaded, it returns nil. // scalar type. If there is no token loaded, it returns nil.
func (d *Dispenser) ScalarVal() interface{} { func (d *Dispenser) ScalarVal() any {
if d.cursor < 0 || d.cursor >= len(d.tokens) { if d.cursor < 0 || d.cursor >= len(d.tokens) {
return nil return nil
} }
@ -412,7 +412,7 @@ func (d *Dispenser) Err(msg string) error {
} }
// Errf is like Err, but for formatted error messages // Errf is like Err, but for formatted error messages
func (d *Dispenser) Errf(format string, args ...interface{}) error { func (d *Dispenser) Errf(format string, args ...any) error {
return d.WrapErr(fmt.Errorf(format, args...)) return d.WrapErr(fmt.Errorf(format, args...))
} }

View file

@ -24,7 +24,7 @@ import (
// Adapter is a type which can adapt a configuration to Caddy JSON. // Adapter is a type which can adapt a configuration to Caddy JSON.
// It returns the results and any warnings, or an error. // It returns the results and any warnings, or an error.
type Adapter interface { type Adapter interface {
Adapt(body []byte, options map[string]interface{}) ([]byte, []Warning, error) Adapt(body []byte, options map[string]any) ([]byte, []Warning, error)
} }
// Warning represents a warning or notice related to conversion. // Warning represents a warning or notice related to conversion.
@ -48,7 +48,7 @@ func (w Warning) String() string {
// are converted to warnings. This is convenient when filling config // are converted to warnings. This is convenient when filling config
// structs that require a json.RawMessage, without having to worry // structs that require a json.RawMessage, without having to worry
// about errors. // about errors.
func JSON(val interface{}, warnings *[]Warning) json.RawMessage { func JSON(val any, warnings *[]Warning) json.RawMessage {
b, err := json.Marshal(val) b, err := json.Marshal(val)
if err != nil { if err != nil {
if warnings != nil { if warnings != nil {
@ -64,9 +64,9 @@ func JSON(val interface{}, warnings *[]Warning) json.RawMessage {
// for encoding module values where the module name has to be described within // for encoding module values where the module name has to be described within
// the object by a certain key; for example, `"handler": "file_server"` for a // the object by a certain key; for example, `"handler": "file_server"` for a
// file server HTTP handler (fieldName="handler" and fieldVal="file_server"). // file server HTTP handler (fieldName="handler" and fieldVal="file_server").
// The val parameter must encode into a map[string]interface{} (i.e. it must be // The val parameter must encode into a map[string]any (i.e. it must be
// a struct or map). Any errors are converted into warnings. // a struct or map). Any errors are converted into warnings.
func JSONModuleObject(val interface{}, fieldName, fieldVal string, warnings *[]Warning) json.RawMessage { func JSONModuleObject(val any, fieldName, fieldVal string, warnings *[]Warning) json.RawMessage {
// encode to a JSON object first // encode to a JSON object first
enc, err := json.Marshal(val) enc, err := json.Marshal(val)
if err != nil { if err != nil {
@ -77,7 +77,7 @@ func JSONModuleObject(val interface{}, fieldName, fieldVal string, warnings *[]W
} }
// then decode the object // then decode the object
var tmp map[string]interface{} var tmp map[string]any
err = json.Unmarshal(enc, &tmp) err = json.Unmarshal(enc, &tmp)
if err != nil { if err != nil {
if warnings != nil { if warnings != nil {

View file

@ -76,7 +76,7 @@ import (
// multiple addresses to the same lists of server blocks (a many:many mapping). // multiple addresses to the same lists of server blocks (a many:many mapping).
// (Doing this is essentially a map-reduce technique.) // (Doing this is essentially a map-reduce technique.)
func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock, func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock,
options map[string]interface{}) (map[string][]serverBlock, error) { options map[string]any) (map[string][]serverBlock, error) {
sbmap := make(map[string][]serverBlock) sbmap := make(map[string][]serverBlock)
for i, sblock := range originalServerBlocks { for i, sblock := range originalServerBlocks {
@ -186,7 +186,7 @@ func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]se
// listenerAddrsForServerBlockKey essentially converts the Caddyfile // listenerAddrsForServerBlockKey essentially converts the Caddyfile
// site addresses to Caddy listener addresses for each server block. // site addresses to Caddy listener addresses for each server block.
func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string, func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string,
options map[string]interface{}) ([]string, error) { options map[string]any) ([]string, error) {
addr, err := ParseAddress(key) addr, err := ParseAddress(key)
if err != nil { if err != nil {
return nil, fmt.Errorf("parsing key: %v", err) return nil, fmt.Errorf("parsing key: %v", err)

View file

@ -142,8 +142,8 @@ func RegisterGlobalOption(opt string, setupFunc UnmarshalGlobalFunc) {
type Helper struct { type Helper struct {
*caddyfile.Dispenser *caddyfile.Dispenser
// State stores intermediate variables during caddyfile adaptation. // State stores intermediate variables during caddyfile adaptation.
State map[string]interface{} State map[string]any
options map[string]interface{} options map[string]any
warnings *[]caddyconfig.Warning warnings *[]caddyconfig.Warning
matcherDefs map[string]caddy.ModuleMap matcherDefs map[string]caddy.ModuleMap
parentBlock caddyfile.ServerBlock parentBlock caddyfile.ServerBlock
@ -151,7 +151,7 @@ type Helper struct {
} }
// Option gets the option keyed by name. // Option gets the option keyed by name.
func (h Helper) Option(name string) interface{} { func (h Helper) Option(name string) any {
return h.options[name] return h.options[name]
} }
@ -175,7 +175,7 @@ func (h Helper) Caddyfiles() []string {
} }
// JSON converts val into JSON. Any errors are added to warnings. // JSON converts val into JSON. Any errors are added to warnings.
func (h Helper) JSON(val interface{}) json.RawMessage { func (h Helper) JSON(val any) json.RawMessage {
return caddyconfig.JSON(val, h.warnings) return caddyconfig.JSON(val, h.warnings)
} }
@ -375,7 +375,7 @@ type ConfigValue struct {
// The value to be used when building the config. // The value to be used when building the config.
// Generally its type is associated with the // Generally its type is associated with the
// name of the Class. // name of the Class.
Value interface{} Value any
directive string directive string
} }
@ -567,7 +567,7 @@ type (
// tokens from a global option. It is passed the tokens to parse and // tokens from a global option. It is passed the tokens to parse and
// existing value from the previous instance of this global option // existing value from the previous instance of this global option
// (if any). It returns the value to associate with this global option. // (if any). It returns the value to associate with this global option.
UnmarshalGlobalFunc func(d *caddyfile.Dispenser, existingVal interface{}) (interface{}, error) UnmarshalGlobalFunc func(d *caddyfile.Dispenser, existingVal any) (any, error)
) )
var registeredDirectives = make(map[string]UnmarshalFunc) var registeredDirectives = make(map[string]UnmarshalFunc)

View file

@ -53,10 +53,10 @@ type ServerType struct {
// Setup makes a config from the tokens. // Setup makes a config from the tokens.
func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock, func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
options map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error) { options map[string]any) (*caddy.Config, []caddyconfig.Warning, error) {
var warnings []caddyconfig.Warning var warnings []caddyconfig.Warning
gc := counter{new(int)} gc := counter{new(int)}
state := make(map[string]interface{}) state := make(map[string]any)
// load all the server blocks and associate them with a "pile" of config values // load all the server blocks and associate them with a "pile" of config values
originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks)) originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks))
@ -313,14 +313,14 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
// which is expected to be the first server block if it has zero // which is expected to be the first server block if it has zero
// keys. It returns the updated list of server blocks with the // keys. It returns the updated list of server blocks with the
// global options block removed, and updates options accordingly. // global options block removed, and updates options accordingly.
func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options map[string]interface{}) ([]serverBlock, error) { func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options map[string]any) ([]serverBlock, error) {
if len(serverBlocks) == 0 || len(serverBlocks[0].block.Keys) > 0 { if len(serverBlocks) == 0 || len(serverBlocks[0].block.Keys) > 0 {
return serverBlocks, nil return serverBlocks, nil
} }
for _, segment := range serverBlocks[0].block.Segments { for _, segment := range serverBlocks[0].block.Segments {
opt := segment.Directive() opt := segment.Directive()
var val interface{} var val any
var err error var err error
disp := caddyfile.NewDispenser(segment) disp := caddyfile.NewDispenser(segment)
@ -390,7 +390,7 @@ func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options
// to server blocks. Each pairing is essentially a server definition. // to server blocks. Each pairing is essentially a server definition.
func (st *ServerType) serversFromPairings( func (st *ServerType) serversFromPairings(
pairings []sbAddrAssociation, pairings []sbAddrAssociation,
options map[string]interface{}, options map[string]any,
warnings *[]caddyconfig.Warning, warnings *[]caddyconfig.Warning,
groupCounter counter, groupCounter counter,
) (map[string]*caddyhttp.Server, error) { ) (map[string]*caddyhttp.Server, error) {
@ -725,7 +725,7 @@ func (st *ServerType) serversFromPairings(
return servers, nil return servers, nil
} }
func detectConflictingSchemes(srv *caddyhttp.Server, serverBlocks []serverBlock, options map[string]interface{}) error { func detectConflictingSchemes(srv *caddyhttp.Server, serverBlocks []serverBlock, options map[string]any) error {
httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort) httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort)
if hp, ok := options["http_port"].(int); ok { if hp, ok := options["http_port"].(int); ok {
httpPort = strconv.Itoa(hp) httpPort = strconv.Itoa(hp)
@ -1304,7 +1304,7 @@ func WasReplacedPlaceholderShorthand(token string) string {
// tryInt tries to convert val to an integer. If it fails, // tryInt tries to convert val to an integer. If it fails,
// it downgrades the error to a warning and returns 0. // it downgrades the error to a warning and returns 0.
func tryInt(val interface{}, warnings *[]caddyconfig.Warning) int { func tryInt(val any, warnings *[]caddyconfig.Warning) int {
intVal, ok := val.(int) intVal, ok := val.(int)
if val != nil && !ok && warnings != nil { if val != nil && !ok && warnings != nil {
*warnings = append(*warnings, caddyconfig.Warning{Message: "not an integer type"}) *warnings = append(*warnings, caddyconfig.Warning{Message: "not an integer type"})
@ -1312,7 +1312,7 @@ func tryInt(val interface{}, warnings *[]caddyconfig.Warning) int {
return intVal return intVal
} }
func tryString(val interface{}, warnings *[]caddyconfig.Warning) string { func tryString(val any, warnings *[]caddyconfig.Warning) string {
stringVal, ok := val.(string) stringVal, ok := val.(string)
if val != nil && !ok && warnings != nil { if val != nil && !ok && warnings != nil {
*warnings = append(*warnings, caddyconfig.Warning{Message: "not a string type"}) *warnings = append(*warnings, caddyconfig.Warning{Message: "not a string type"})
@ -1320,7 +1320,7 @@ func tryString(val interface{}, warnings *[]caddyconfig.Warning) string {
return stringVal return stringVal
} }
func tryDuration(val interface{}, warnings *[]caddyconfig.Warning) caddy.Duration { func tryDuration(val any, warnings *[]caddyconfig.Warning) caddy.Duration {
durationVal, ok := val.(caddy.Duration) durationVal, ok := val.(caddy.Duration)
if val != nil && !ok && warnings != nil { if val != nil && !ok && warnings != nil {
*warnings = append(*warnings, caddyconfig.Warning{Message: "not a duration type"}) *warnings = append(*warnings, caddyconfig.Warning{Message: "not a duration type"})

View file

@ -54,9 +54,9 @@ func init() {
RegisterGlobalOption("preferred_chains", parseOptPreferredChains) RegisterGlobalOption("preferred_chains", parseOptPreferredChains)
} }
func parseOptTrue(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { return true, nil } func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil }
func parseOptHTTPPort(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) {
var httpPort int var httpPort int
for d.Next() { for d.Next() {
var httpPortStr string var httpPortStr string
@ -72,7 +72,7 @@ func parseOptHTTPPort(d *caddyfile.Dispenser, _ interface{}) (interface{}, error
return httpPort, nil return httpPort, nil
} }
func parseOptHTTPSPort(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) {
var httpsPort int var httpsPort int
for d.Next() { for d.Next() {
var httpsPortStr string var httpsPortStr string
@ -88,7 +88,7 @@ func parseOptHTTPSPort(d *caddyfile.Dispenser, _ interface{}) (interface{}, erro
return httpsPort, nil return httpsPort, nil
} }
func parseOptOrder(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
newOrder := directiveOrder newOrder := directiveOrder
for d.Next() { for d.Next() {
@ -164,7 +164,7 @@ func parseOptOrder(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) {
return newOrder, nil return newOrder, nil
} }
func parseOptStorage(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptStorage(d *caddyfile.Dispenser, _ any) (any, error) {
if !d.Next() { // consume option name if !d.Next() { // consume option name
return nil, d.ArgErr() return nil, d.ArgErr()
} }
@ -183,7 +183,7 @@ func parseOptStorage(d *caddyfile.Dispenser, _ interface{}) (interface{}, error)
return storage, nil return storage, nil
} }
func parseOptDuration(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptDuration(d *caddyfile.Dispenser, _ any) (any, error) {
if !d.Next() { // consume option name if !d.Next() { // consume option name
return nil, d.ArgErr() return nil, d.ArgErr()
} }
@ -197,7 +197,7 @@ func parseOptDuration(d *caddyfile.Dispenser, _ interface{}) (interface{}, error
return caddy.Duration(dur), nil return caddy.Duration(dur), nil
} }
func parseOptACMEDNS(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptACMEDNS(d *caddyfile.Dispenser, _ any) (any, error) {
if !d.Next() { // consume option name if !d.Next() { // consume option name
return nil, d.ArgErr() return nil, d.ArgErr()
} }
@ -216,7 +216,7 @@ func parseOptACMEDNS(d *caddyfile.Dispenser, _ interface{}) (interface{}, error)
return prov, nil return prov, nil
} }
func parseOptACMEEAB(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) {
eab := new(acme.EAB) eab := new(acme.EAB)
for d.Next() { for d.Next() {
if d.NextArg() { if d.NextArg() {
@ -244,7 +244,7 @@ func parseOptACMEEAB(d *caddyfile.Dispenser, _ interface{}) (interface{}, error)
return eab, nil return eab, nil
} }
func parseOptCertIssuer(d *caddyfile.Dispenser, existing interface{}) (interface{}, error) { func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) {
var issuers []certmagic.Issuer var issuers []certmagic.Issuer
if existing != nil { if existing != nil {
issuers = existing.([]certmagic.Issuer) issuers = existing.([]certmagic.Issuer)
@ -267,7 +267,7 @@ func parseOptCertIssuer(d *caddyfile.Dispenser, existing interface{}) (interface
return issuers, nil return issuers, nil
} }
func parseOptSingleString(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) {
d.Next() // consume parameter name d.Next() // consume parameter name
if !d.Next() { if !d.Next() {
return "", d.ArgErr() return "", d.ArgErr()
@ -279,7 +279,7 @@ func parseOptSingleString(d *caddyfile.Dispenser, _ interface{}) (interface{}, e
return val, nil return val, nil
} }
func parseOptStringList(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptStringList(d *caddyfile.Dispenser, _ any) (any, error) {
d.Next() // consume parameter name d.Next() // consume parameter name
val := d.RemainingArgs() val := d.RemainingArgs()
if len(val) == 0 { if len(val) == 0 {
@ -288,7 +288,7 @@ func parseOptStringList(d *caddyfile.Dispenser, _ interface{}) (interface{}, err
return val, nil return val, nil
} }
func parseOptAdmin(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
adminCfg := new(caddy.AdminConfig) adminCfg := new(caddy.AdminConfig)
for d.Next() { for d.Next() {
if d.NextArg() { if d.NextArg() {
@ -324,7 +324,7 @@ func parseOptAdmin(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) {
return adminCfg, nil return adminCfg, nil
} }
func parseOptOnDemand(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
var ond *caddytls.OnDemandConfig var ond *caddytls.OnDemandConfig
for d.Next() { for d.Next() {
if d.NextArg() { if d.NextArg() {
@ -384,7 +384,7 @@ func parseOptOnDemand(d *caddyfile.Dispenser, _ interface{}) (interface{}, error
return ond, nil return ond, nil
} }
func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) {
d.Next() // consume parameter name d.Next() // consume parameter name
if !d.Next() { if !d.Next() {
return "", d.ArgErr() return "", d.ArgErr()
@ -399,11 +399,11 @@ func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ interface{}) (interface{}, erro
return val, nil return val, nil
} }
func parseServerOptions(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseServerOptions(d *caddyfile.Dispenser, _ any) (any, error) {
return unmarshalCaddyfileServerOptions(d) return unmarshalCaddyfileServerOptions(d)
} }
func parseOCSPStaplingOptions(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOCSPStaplingOptions(d *caddyfile.Dispenser, _ any) (any, error) {
d.Next() // consume option name d.Next() // consume option name
var val string var val string
if !d.AllArgs(&val) { if !d.AllArgs(&val) {
@ -429,8 +429,7 @@ func parseOCSPStaplingOptions(d *caddyfile.Dispenser, _ interface{}) (interface{
// //
// When the name argument is unspecified, this directive modifies the default // When the name argument is unspecified, this directive modifies the default
// logger. // logger.
// func parseLogOptions(d *caddyfile.Dispenser, existingVal any) (any, error) {
func parseLogOptions(d *caddyfile.Dispenser, existingVal interface{}) (interface{}, error) {
currentNames := make(map[string]struct{}) currentNames := make(map[string]struct{})
if existingVal != nil { if existingVal != nil {
innerVals, ok := existingVal.([]ConfigValue) innerVals, ok := existingVal.([]ConfigValue)
@ -465,7 +464,7 @@ func parseLogOptions(d *caddyfile.Dispenser, existingVal interface{}) (interface
return configValues, nil return configValues, nil
} }
func parseOptPreferredChains(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) { func parseOptPreferredChains(d *caddyfile.Dispenser, _ any) (any, error) {
d.Next() d.Next()
return caddytls.ParseCaddyfilePreferredChainsOptions(d) return caddytls.ParseCaddyfilePreferredChainsOptions(d)
} }

View file

@ -45,8 +45,7 @@ func init() {
// } // }
// //
// When the CA ID is unspecified, 'local' is assumed. // When the CA ID is unspecified, 'local' is assumed.
// func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
func parsePKIApp(d *caddyfile.Dispenser, existingVal interface{}) (interface{}, error) {
pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)} pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}
for d.Next() { for d.Next() {
@ -160,7 +159,7 @@ func parsePKIApp(d *caddyfile.Dispenser, existingVal interface{}) (interface{},
func (st ServerType) buildPKIApp( func (st ServerType) buildPKIApp(
pairings []sbAddrAssociation, pairings []sbAddrAssociation,
options map[string]interface{}, options map[string]any,
warnings []caddyconfig.Warning, warnings []caddyconfig.Warning,
) (*caddypki.PKI, []caddyconfig.Warning, error) { ) (*caddypki.PKI, []caddyconfig.Warning, error) {

View file

@ -45,7 +45,7 @@ type serverOptions struct {
ShouldLogCredentials bool ShouldLogCredentials bool
} }
func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (interface{}, error) { func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
serverOpts := serverOptions{} serverOpts := serverOptions{}
for d.Next() { for d.Next() {
if d.NextArg() { if d.NextArg() {
@ -182,7 +182,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (interface{}, error
// applyServerOptions sets the server options on the appropriate servers // applyServerOptions sets the server options on the appropriate servers
func applyServerOptions( func applyServerOptions(
servers map[string]*caddyhttp.Server, servers map[string]*caddyhttp.Server,
options map[string]interface{}, options map[string]any,
warnings *[]caddyconfig.Warning, warnings *[]caddyconfig.Warning,
) error { ) error {
// If experimental HTTP/3 is enabled, enable it on each server. // If experimental HTTP/3 is enabled, enable it on each server.

View file

@ -33,7 +33,7 @@ import (
func (st ServerType) buildTLSApp( func (st ServerType) buildTLSApp(
pairings []sbAddrAssociation, pairings []sbAddrAssociation,
options map[string]interface{}, options map[string]any,
warnings []caddyconfig.Warning, warnings []caddyconfig.Warning,
) (*caddytls.TLS, []caddyconfig.Warning, error) { ) (*caddytls.TLS, []caddyconfig.Warning, error) {
@ -420,7 +420,7 @@ func (st ServerType) buildTLSApp(
type acmeCapable interface{ GetACMEIssuer() *caddytls.ACMEIssuer } type acmeCapable interface{ GetACMEIssuer() *caddytls.ACMEIssuer }
func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]interface{}) error { func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) error {
acmeWrapper, ok := issuer.(acmeCapable) acmeWrapper, ok := issuer.(acmeCapable)
if !ok { if !ok {
return nil return nil
@ -467,7 +467,7 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]interf
// for any other automation policies. A nil policy (and no error) will be // for any other automation policies. A nil policy (and no error) will be
// returned if there are no default/global options. However, if always is // returned if there are no default/global options. However, if always is
// true, a non-nil value will always be returned (unless there is an error). // true, a non-nil value will always be returned (unless there is an error).
func newBaseAutomationPolicy(options map[string]interface{}, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) { func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) {
issuers, hasIssuers := options["cert_issuer"] issuers, hasIssuers := options["cert_issuer"]
_, hasLocalCerts := options["local_certs"] _, hasLocalCerts := options["local_certs"]
keyType, hasKeyType := options["key_type"] keyType, hasKeyType := options["key_type"]

View file

@ -209,7 +209,7 @@ func adaptByContentType(contentType string, body []byte) ([]byte, []Warning, err
} }
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -186,7 +186,7 @@ func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error
expectedBytes, _, _ = adapter.Adapt([]byte(rawConfig), nil) expectedBytes, _, _ = adapter.Adapt([]byte(rawConfig), nil)
} }
var expected interface{} var expected any
err := json.Unmarshal(expectedBytes, &expected) err := json.Unmarshal(expectedBytes, &expected)
if err != nil { if err != nil {
return err return err
@ -196,7 +196,7 @@ func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error
Timeout: Default.LoadRequestTimeout, Timeout: Default.LoadRequestTimeout,
} }
fetchConfig := func(client *http.Client) interface{} { fetchConfig := func(client *http.Client) any {
resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", Default.AdminPort)) resp, err := client.Get(fmt.Sprintf("http://localhost:%d/config/", Default.AdminPort))
if err != nil { if err != nil {
return nil return nil
@ -206,7 +206,7 @@ func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error
if err != nil { if err != nil {
return nil return nil
} }
var actual interface{} var actual any
err = json.Unmarshal(actualBytes, &actual) err = json.Unmarshal(actualBytes, &actual)
if err != nil { if err != nil {
return nil return nil
@ -371,7 +371,7 @@ func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string,
return false return false
} }
options := make(map[string]interface{}) options := make(map[string]any)
result, warnings, err := cfgAdapter.Adapt([]byte(rawConfig), options) result, warnings, err := cfgAdapter.Adapt([]byte(rawConfig), options)
if err != nil { if err != nil {

View file

@ -471,7 +471,7 @@ func cmdAdaptConfig(fl Flags) (int, error) {
fmt.Errorf("reading input file: %v", err) fmt.Errorf("reading input file: %v", err)
} }
opts := map[string]interface{}{"filename": adaptCmdInputFlag} opts := map[string]any{"filename": adaptCmdInputFlag}
adaptedConfig, warnings, err := cfgAdapter.Adapt(input, opts) adaptedConfig, warnings, err := cfgAdapter.Adapt(input, opts)
if err != nil { if err != nil {

View file

@ -173,7 +173,7 @@ func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
// adapt config // adapt config
if cfgAdapter != nil { if cfgAdapter != nil {
adaptedConfig, warnings, err := cfgAdapter.Adapt(config, map[string]interface{}{ adaptedConfig, warnings, err := cfgAdapter.Adapt(config, map[string]any{
"filename": configFile, "filename": configFile,
}) })
if err != nil { if err != nil {

View file

@ -194,7 +194,7 @@ func getModules() (standard, nonstandard, unknown []moduleInfo, err error) {
// can use reflection but we need a non-pointer value (I'm // can use reflection but we need a non-pointer value (I'm
// not sure why), and since New() should return a pointer // not sure why), and since New() should return a pointer
// value, we need to dereference it first // value, we need to dereference it first
iface := interface{}(modInfo.New()) iface := any(modInfo.New())
if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr { if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr {
iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface() iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface()
} }

View file

@ -37,7 +37,7 @@ import (
// not actually need to do this). // not actually need to do this).
type Context struct { type Context struct {
context.Context context.Context
moduleInstances map[string][]interface{} moduleInstances map[string][]any
cfg *Config cfg *Config
cleanupFuncs []func() cleanupFuncs []func()
} }
@ -51,7 +51,7 @@ type Context struct {
// modules which are loaded will be properly unloaded. // modules which are loaded will be properly unloaded.
// See standard library context package's documentation. // See standard library context package's documentation.
func NewContext(ctx Context) (Context, context.CancelFunc) { func NewContext(ctx Context) (Context, context.CancelFunc) {
newCtx := Context{moduleInstances: make(map[string][]interface{}), cfg: ctx.cfg} newCtx := Context{moduleInstances: make(map[string][]any), cfg: ctx.cfg}
c, cancel := context.WithCancel(ctx.Context) c, cancel := context.WithCancel(ctx.Context)
wrappedCancel := func() { wrappedCancel := func() {
cancel() cancel()
@ -90,11 +90,11 @@ func (ctx *Context) OnCancel(f func()) {
// ModuleMap may be used in place of map[string]json.RawMessage. The return value's // ModuleMap may be used in place of map[string]json.RawMessage. The return value's
// underlying type mirrors the input field's type: // underlying type mirrors the input field's type:
// //
// json.RawMessage => interface{} // json.RawMessage => any
// []json.RawMessage => []interface{} // []json.RawMessage => []any
// [][]json.RawMessage => [][]interface{} // [][]json.RawMessage => [][]any
// map[string]json.RawMessage => map[string]interface{} // map[string]json.RawMessage => map[string]any
// []map[string]json.RawMessage => []map[string]interface{} // []map[string]json.RawMessage => []map[string]any
// //
// The field must have a "caddy" struct tag in this format: // The field must have a "caddy" struct tag in this format:
// //
@ -121,14 +121,14 @@ func (ctx *Context) OnCancel(f func()) {
// in order to know the module name. // in order to know the module name.
// //
// To make use of the loaded module(s) (the return value), you will probably want // To make use of the loaded module(s) (the return value), you will probably want
// to type-assert each interface{} value(s) to the types that are useful to you // to type-assert each 'any' value(s) to the types that are useful to you
// and store them on the same struct. Storing them on the same struct makes for // and store them on the same struct. Storing them on the same struct makes for
// easy garbage collection when your host module is no longer needed. // easy garbage collection when your host module is no longer needed.
// //
// Loaded modules have already been provisioned and validated. Upon returning // Loaded modules have already been provisioned and validated. Upon returning
// successfully, this method clears the json.RawMessage(s) in the field since // successfully, this method clears the json.RawMessage(s) in the field since
// the raw JSON is no longer needed, and this allows the GC to free up memory. // the raw JSON is no longer needed, and this allows the GC to free up memory.
func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (interface{}, error) { func (ctx Context) LoadModule(structPointer any, fieldName string) (any, error) {
val := reflect.ValueOf(structPointer).Elem().FieldByName(fieldName) val := reflect.ValueOf(structPointer).Elem().FieldByName(fieldName)
typ := val.Type() typ := val.Type()
@ -148,7 +148,7 @@ func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (inte
} }
inlineModuleKey := opts["inline_key"] inlineModuleKey := opts["inline_key"]
var result interface{} var result any
switch val.Kind() { switch val.Kind() {
case reflect.Slice: case reflect.Slice:
@ -170,7 +170,7 @@ func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (inte
if inlineModuleKey == "" { if inlineModuleKey == "" {
panic("unable to determine module name without inline_key because type is not a ModuleMap") panic("unable to determine module name without inline_key because type is not a ModuleMap")
} }
var all []interface{} var all []any
for i := 0; i < val.Len(); i++ { for i := 0; i < val.Len(); i++ {
val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Index(i).Interface().(json.RawMessage)) val, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, val.Index(i).Interface().(json.RawMessage))
if err != nil { if err != nil {
@ -186,10 +186,10 @@ func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (inte
if inlineModuleKey == "" { if inlineModuleKey == "" {
panic("unable to determine module name without inline_key because type is not a ModuleMap") panic("unable to determine module name without inline_key because type is not a ModuleMap")
} }
var all [][]interface{} var all [][]any
for i := 0; i < val.Len(); i++ { for i := 0; i < val.Len(); i++ {
innerVal := val.Index(i) innerVal := val.Index(i)
var allInner []interface{} var allInner []any
for j := 0; j < innerVal.Len(); j++ { for j := 0; j < innerVal.Len(); j++ {
innerInnerVal, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, innerVal.Index(j).Interface().(json.RawMessage)) innerInnerVal, err := ctx.loadModuleInline(inlineModuleKey, moduleNamespace, innerVal.Index(j).Interface().(json.RawMessage))
if err != nil { if err != nil {
@ -204,7 +204,7 @@ func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (inte
} else if isModuleMapType(typ.Elem()) { } else if isModuleMapType(typ.Elem()) {
// val is `[]map[string]json.RawMessage` // val is `[]map[string]json.RawMessage`
var all []map[string]interface{} var all []map[string]any
for i := 0; i < val.Len(); i++ { for i := 0; i < val.Len(); i++ {
thisSet, err := ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val.Index(i)) thisSet, err := ctx.loadModulesFromSomeMap(moduleNamespace, inlineModuleKey, val.Index(i))
if err != nil { if err != nil {
@ -232,10 +232,10 @@ func (ctx Context) LoadModule(structPointer interface{}, fieldName string) (inte
return result, nil return result, nil
} }
// loadModulesFromSomeMap loads modules from val, which must be a type of map[string]interface{}. // loadModulesFromSomeMap loads modules from val, which must be a type of map[string]any.
// Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module // Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module
// name) or as a regular map (key is not the module name, and module name is defined inline). // name) or as a regular map (key is not the module name, and module name is defined inline).
func (ctx Context) loadModulesFromSomeMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]interface{}, error) { func (ctx Context) loadModulesFromSomeMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]any, error) {
// if no inline_key is specified, then val must be a ModuleMap, // if no inline_key is specified, then val must be a ModuleMap,
// where the key is the module name // where the key is the module name
if inlineModuleKey == "" { if inlineModuleKey == "" {
@ -253,8 +253,8 @@ func (ctx Context) loadModulesFromSomeMap(namespace, inlineModuleKey string, val
// loadModulesFromRegularMap loads modules from val, where val is a map[string]json.RawMessage. // loadModulesFromRegularMap loads modules from val, where val is a map[string]json.RawMessage.
// Map keys are NOT interpreted as module names, so module names are still expected to appear // Map keys are NOT interpreted as module names, so module names are still expected to appear
// inline with the objects. // inline with the objects.
func (ctx Context) loadModulesFromRegularMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]interface{}, error) { func (ctx Context) loadModulesFromRegularMap(namespace, inlineModuleKey string, val reflect.Value) (map[string]any, error) {
mods := make(map[string]interface{}) mods := make(map[string]any)
iter := val.MapRange() iter := val.MapRange()
for iter.Next() { for iter.Next() {
k := iter.Key() k := iter.Key()
@ -268,10 +268,10 @@ func (ctx Context) loadModulesFromRegularMap(namespace, inlineModuleKey string,
return mods, nil return mods, nil
} }
// loadModuleMap loads modules from a ModuleMap, i.e. map[string]interface{}, where the key is the // loadModuleMap loads modules from a ModuleMap, i.e. map[string]any, where the key is the
// module name. With a module map, module names do not need to be defined inline with their values. // module name. With a module map, module names do not need to be defined inline with their values.
func (ctx Context) loadModuleMap(namespace string, val reflect.Value) (map[string]interface{}, error) { func (ctx Context) loadModuleMap(namespace string, val reflect.Value) (map[string]any, error) {
all := make(map[string]interface{}) all := make(map[string]any)
iter := val.MapRange() iter := val.MapRange()
for iter.Next() { for iter.Next() {
k := iter.Key().Interface().(string) k := iter.Key().Interface().(string)
@ -299,7 +299,7 @@ func (ctx Context) loadModuleMap(namespace string, val reflect.Value) (map[strin
// directly by most modules. However, this method is useful when // directly by most modules. However, this method is useful when
// dynamically loading/unloading modules in their own context, // dynamically loading/unloading modules in their own context,
// like from embedded scripts, etc. // like from embedded scripts, etc.
func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (interface{}, error) { func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error) {
modulesMu.RLock() modulesMu.RLock()
mod, ok := modules[id] mod, ok := modules[id]
modulesMu.RUnlock() modulesMu.RUnlock()
@ -311,7 +311,7 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (interface{
return nil, fmt.Errorf("module '%s' has no constructor", mod.ID) return nil, fmt.Errorf("module '%s' has no constructor", mod.ID)
} }
val := mod.New().(interface{}) val := mod.New().(any)
// value must be a pointer for unmarshaling into concrete type, even if // value must be a pointer for unmarshaling into concrete type, even if
// the module's concrete type is a slice or map; New() *should* return // the module's concrete type is a slice or map; New() *should* return
@ -375,7 +375,7 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (interface{
} }
// loadModuleInline loads a module from a JSON raw message which decodes to // loadModuleInline loads a module from a JSON raw message which decodes to
// a map[string]interface{}, where one of the object keys is moduleNameKey // a map[string]any, where one of the object keys is moduleNameKey
// and the corresponding value is the module name (as a string) which can // and the corresponding value is the module name (as a string) which can
// be found in the given scope. In other words, the module name is declared // be found in the given scope. In other words, the module name is declared
// in-line with the module itself. // in-line with the module itself.
@ -385,7 +385,7 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (interface{
// multiple instances in the map or it appears in an array (where there are // multiple instances in the map or it appears in an array (where there are
// no custom keys). In other words, the key containing the module name is // no custom keys). In other words, the key containing the module name is
// treated special/separate from all the other keys in the object. // treated special/separate from all the other keys in the object.
func (ctx Context) loadModuleInline(moduleNameKey, moduleScope string, raw json.RawMessage) (interface{}, error) { func (ctx Context) loadModuleInline(moduleNameKey, moduleScope string, raw json.RawMessage) (any, error) {
moduleName, raw, err := getModuleNameInline(moduleNameKey, raw) moduleName, raw, err := getModuleNameInline(moduleNameKey, raw)
if err != nil { if err != nil {
return nil, err return nil, err
@ -407,7 +407,7 @@ func (ctx Context) loadModuleInline(moduleNameKey, moduleScope string, raw json.
// called during the Provision/Validate phase to reference a // called during the Provision/Validate phase to reference a
// module's own host app (since the parent app module is still // module's own host app (since the parent app module is still
// in the process of being provisioned, it is not yet ready). // in the process of being provisioned, it is not yet ready).
func (ctx Context) App(name string) (interface{}, error) { func (ctx Context) App(name string) (any, error) {
if app, ok := ctx.cfg.apps[name]; ok { if app, ok := ctx.cfg.apps[name]; ok {
return app, nil return app, nil
} }

View file

@ -71,13 +71,13 @@ func ExampleContext_LoadModule_array() {
}, },
} }
// since our input is []json.RawMessage, the output will be []interface{} // since our input is []json.RawMessage, the output will be []any
mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw") mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw")
if err != nil { if err != nil {
// you'd want to actually handle the error here // you'd want to actually handle the error here
// return fmt.Errorf("loading guest modules: %v", err) // return fmt.Errorf("loading guest modules: %v", err)
} }
for _, mod := range mods.([]interface{}) { for _, mod := range mods.([]any) {
myStruct.guestModules = append(myStruct.guestModules, mod.(io.Writer)) myStruct.guestModules = append(myStruct.guestModules, mod.(io.Writer))
} }
@ -104,13 +104,13 @@ func ExampleContext_LoadModule_map() {
}, },
} }
// since our input is map[string]json.RawMessage, the output will be map[string]interface{} // since our input is map[string]json.RawMessage, the output will be map[string]any
mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw") mods, err := ctx.LoadModule(myStruct, "GuestModulesRaw")
if err != nil { if err != nil {
// you'd want to actually handle the error here // you'd want to actually handle the error here
// return fmt.Errorf("loading guest modules: %v", err) // return fmt.Errorf("loading guest modules: %v", err)
} }
for modName, mod := range mods.(map[string]interface{}) { for modName, mod := range mods.(map[string]any) {
myStruct.guestModules[modName] = mod.(io.Writer) myStruct.guestModules[modName] = mod.(io.Writer)
} }

2
go.mod
View file

@ -1,6 +1,6 @@
module github.com/caddyserver/caddy/v2 module github.com/caddyserver/caddy/v2
go 1.17 go 1.18
require ( require (
github.com/BurntSushi/toml v1.2.0 github.com/BurntSushi/toml v1.2.0

371
go.sum

File diff suppressed because it is too large Load diff

View file

@ -44,7 +44,7 @@ import (
// Provisioner, the Provision() method is called. 4) If the // Provisioner, the Provision() method is called. 4) If the
// module is a Validator, the Validate() method is called. // module is a Validator, the Validate() method is called.
// 5) The module will probably be type-asserted from // 5) The module will probably be type-asserted from
// interface{} to some other, more useful interface expected // 'any' to some other, more useful interface expected
// by the host module. For example, HTTP handler modules are // by the host module. For example, HTTP handler modules are
// type-asserted as caddyhttp.MiddlewareHandler values. // type-asserted as caddyhttp.MiddlewareHandler values.
// 6) When a module's containing Context is canceled, if it is // 6) When a module's containing Context is canceled, if it is
@ -172,7 +172,7 @@ func GetModule(name string) (ModuleInfo, error) {
// GetModuleName returns a module's name (the last label of its ID) // GetModuleName returns a module's name (the last label of its ID)
// from an instance of its value. If the value is not a module, an // from an instance of its value. If the value is not a module, an
// empty string will be returned. // empty string will be returned.
func GetModuleName(instance interface{}) string { func GetModuleName(instance any) string {
var name string var name string
if mod, ok := instance.(Module); ok { if mod, ok := instance.(Module); ok {
name = mod.CaddyModule().ID.Name() name = mod.CaddyModule().ID.Name()
@ -182,7 +182,7 @@ func GetModuleName(instance interface{}) string {
// GetModuleID returns a module's ID from an instance of its value. // GetModuleID returns a module's ID from an instance of its value.
// If the value is not a module, an empty string will be returned. // If the value is not a module, an empty string will be returned.
func GetModuleID(instance interface{}) string { func GetModuleID(instance any) string {
var id string var id string
if mod, ok := instance.(Module); ok { if mod, ok := instance.(Module); ok {
id = string(mod.CaddyModule().ID) id = string(mod.CaddyModule().ID)
@ -259,7 +259,7 @@ func Modules() []string {
// where raw must be a JSON encoding of a map. It returns that value, // where raw must be a JSON encoding of a map. It returns that value,
// along with the result of removing that key from raw. // along with the result of removing that key from raw.
func getModuleNameInline(moduleNameKey string, raw json.RawMessage) (string, json.RawMessage, error) { func getModuleNameInline(moduleNameKey string, raw json.RawMessage) (string, json.RawMessage, error) {
var tmp map[string]interface{} var tmp map[string]any
err := json.Unmarshal(raw, &tmp) err := json.Unmarshal(raw, &tmp)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
@ -337,7 +337,7 @@ func ParseStructTag(tag string) (map[string]string, error) {
// if any of the fields are unrecognized. Useful when decoding // if any of the fields are unrecognized. Useful when decoding
// module configurations, where you want to be more sure they're // module configurations, where you want to be more sure they're
// correct. // correct.
func strictUnmarshalJSON(data []byte, v interface{}) error { func strictUnmarshalJSON(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data)) dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields() dec.DisallowUnknownFields()
return dec.Decode(v) return dec.Decode(v)

View file

@ -202,7 +202,7 @@ func (app *App) Provision(ctx caddy.Context) error {
return fmt.Errorf("loading listener wrapper modules: %v", err) return fmt.Errorf("loading listener wrapper modules: %v", err)
} }
var hasTLSPlaceholder bool var hasTLSPlaceholder bool
for i, val := range vals.([]interface{}) { for i, val := range vals.([]any) {
if _, ok := val.(*tlsPlaceholderWrapper); ok { if _, ok := val.(*tlsPlaceholderWrapper); ok {
if i == 0 { if i == 0 {
// putting the tls placeholder wrapper first is nonsensical because // putting the tls placeholder wrapper first is nonsensical because

View file

@ -62,7 +62,7 @@ func (a *Authentication) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading authentication providers: %v", err) return fmt.Errorf("loading authentication providers: %v", err)
} }
for modName, modIface := range mods.(map[string]interface{}) { for modName, modIface := range mods.(map[string]any) {
a.Providers[modName] = modIface.(Authenticator) a.Providers[modName] = modIface.(Authenticator)
} }
return nil return nil

View file

@ -218,7 +218,7 @@ var httpRequestCELType = types.NewTypeValue("http.Request", traits.ReceiverType)
// drops allocation costs for CEL expression evaluations by roughly half. // drops allocation costs for CEL expression evaluations by roughly half.
type celHTTPRequest struct{ *http.Request } type celHTTPRequest struct{ *http.Request }
func (cr celHTTPRequest) ResolveName(name string) (interface{}, bool) { func (cr celHTTPRequest) ResolveName(name string) (any, bool) {
if name == "request" { if name == "request" {
return cr, true return cr, true
} }
@ -229,7 +229,7 @@ func (cr celHTTPRequest) Parent() interpreter.Activation {
return nil return nil
} }
func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) {
return cr.Request, nil return cr.Request, nil
} }
func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val { func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val {
@ -241,8 +241,8 @@ func (cr celHTTPRequest) Equal(other ref.Val) ref.Val {
} }
return types.ValOrErr(other, "%v is not comparable type", other) return types.ValOrErr(other, "%v is not comparable type", other)
} }
func (celHTTPRequest) Type() ref.Type { return httpRequestCELType } func (celHTTPRequest) Type() ref.Type { return httpRequestCELType }
func (cr celHTTPRequest) Value() interface{} { return cr } func (cr celHTTPRequest) Value() any { return cr }
var pkixNameCELType = types.NewTypeValue("pkix.Name", traits.ReceiverType) var pkixNameCELType = types.NewTypeValue("pkix.Name", traits.ReceiverType)
@ -250,7 +250,7 @@ var pkixNameCELType = types.NewTypeValue("pkix.Name", traits.ReceiverType)
// methods to satisfy the ref.Val interface. // methods to satisfy the ref.Val interface.
type celPkixName struct{ *pkix.Name } type celPkixName struct{ *pkix.Name }
func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) {
return pn.Name, nil return pn.Name, nil
} }
func (celPkixName) ConvertToType(typeVal ref.Type) ref.Val { func (celPkixName) ConvertToType(typeVal ref.Type) ref.Val {
@ -262,13 +262,13 @@ func (pn celPkixName) Equal(other ref.Val) ref.Val {
} }
return types.ValOrErr(other, "%v is not comparable type", other) return types.ValOrErr(other, "%v is not comparable type", other)
} }
func (celPkixName) Type() ref.Type { return pkixNameCELType } func (celPkixName) Type() ref.Type { return pkixNameCELType }
func (pn celPkixName) Value() interface{} { return pn } func (pn celPkixName) Value() any { return pn }
// celTypeAdapter can adapt our custom types to a CEL value. // celTypeAdapter can adapt our custom types to a CEL value.
type celTypeAdapter struct{} type celTypeAdapter struct{}
func (celTypeAdapter) NativeToValue(value interface{}) ref.Val { func (celTypeAdapter) NativeToValue(value any) ref.Val {
switch v := value.(type) { switch v := value.(type) {
case celHTTPRequest: case celHTTPRequest:
return v return v
@ -545,17 +545,17 @@ func celMatcherJSONMacroExpander(funcName string) parser.MacroExpander {
// CELValueToMapStrList converts a CEL value to a map[string][]string // CELValueToMapStrList converts a CEL value to a map[string][]string
// //
// Earlier validation stages should guarantee that the value has this type // Earlier validation stages should guarantee that the value has this type
// at compile time, and that the runtime value type is map[string]interface{}. // at compile time, and that the runtime value type is map[string]any.
// The reason for the slight difference in value type is that CEL allows for // The reason for the slight difference in value type is that CEL allows for
// map literals containing heterogeneous values, in this case string and list // map literals containing heterogeneous values, in this case string and list
// of string. // of string.
func CELValueToMapStrList(data ref.Val) (map[string][]string, error) { func CELValueToMapStrList(data ref.Val) (map[string][]string, error) {
mapStrType := reflect.TypeOf(map[string]interface{}{}) mapStrType := reflect.TypeOf(map[string]any{})
mapStrRaw, err := data.ConvertToNative(mapStrType) mapStrRaw, err := data.ConvertToNative(mapStrType)
if err != nil { if err != nil {
return nil, err return nil, err
} }
mapStrIface := mapStrRaw.(map[string]interface{}) mapStrIface := mapStrRaw.(map[string]any)
mapStrListStr := make(map[string][]string, len(mapStrIface)) mapStrListStr := make(map[string][]string, len(mapStrIface))
for k, v := range mapStrIface { for k, v := range mapStrIface {
switch val := v.(type) { switch val := v.(type) {

View file

@ -71,7 +71,7 @@ func (enc *Encode) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading encoder modules: %v", err) return fmt.Errorf("loading encoder modules: %v", err)
} }
for modName, modIface := range mods.(map[string]interface{}) { for modName, modIface := range mods.(map[string]any) {
err = enc.addEncoding(modIface.(Encoding)) err = enc.addEncoding(modIface.(Encoding))
if err != nil { if err != nil {
return fmt.Errorf("adding encoding %s: %v", modName, err) return fmt.Errorf("adding encoding %s: %v", modName, err)
@ -142,7 +142,7 @@ func (enc *Encode) addEncoding(e Encoding) error {
enc.writerPools = make(map[string]*sync.Pool) enc.writerPools = make(map[string]*sync.Pool)
} }
enc.writerPools[ae] = &sync.Pool{ enc.writerPools[ae] = &sync.Pool{
New: func() interface{} { New: func() any {
return e.NewEncoder() return e.NewEncoder()
}, },
} }
@ -418,7 +418,7 @@ type Precompressed interface {
} }
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -231,7 +231,7 @@ type templateContext struct {
// bufPool is used to increase the efficiency of file listings. // bufPool is used to increase the efficiency of file listings.
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -205,7 +205,7 @@ func (fsrv *FileServer) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading encoder modules: %v", err) return fmt.Errorf("loading encoder modules: %v", err)
} }
for modName, modIface := range mods.(map[string]interface{}) { for modName, modIface := range mods.(map[string]any) {
p, ok := modIface.(encode.Precompressed) p, ok := modIface.(encode.Precompressed)
if !ok { if !ok {
return fmt.Errorf("module %s is not precompressor", modName) return fmt.Errorf("module %s is not precompressor", modName)

View file

@ -78,7 +78,7 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error)
// every other line maps one input to one or more outputs // every other line maps one input to one or more outputs
in := h.Val() in := h.Val()
var outs []interface{} var outs []any
for h.NextArg() { for h.NextArg() {
val := h.ScalarVal() val := h.ScalarVal()
if val == "-" { if val == "-" {

View file

@ -119,7 +119,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
// defer work until a variable is actually evaluated by using replacer's Map callback // defer work until a variable is actually evaluated by using replacer's Map callback
repl.Map(func(key string) (interface{}, bool) { repl.Map(func(key string) (any, bool) {
// return early if the variable is not even a configured destination // return early if the variable is not even a configured destination
destIdx := h.destinationIndex(key) destIdx := h.destinationIndex(key)
if destIdx < 0 { if destIdx < 0 {
@ -187,7 +187,7 @@ type Mapping struct {
// Upon a match with the input, each output is positionally correlated // Upon a match with the input, each output is positionally correlated
// with each destination of the parent handler. An output that is null // with each destination of the parent handler. An output that is null
// (nil) will be treated as if it was not mapped at all. // (nil) will be treated as if it was not mapped at all.
Outputs []interface{} `json:"outputs,omitempty"` Outputs []any `json:"outputs,omitempty"`
re *regexp.Regexp re *regexp.Regexp
} }

View file

@ -15,7 +15,7 @@ func TestHandler(t *testing.T) {
for i, tc := range []struct { for i, tc := range []struct {
handler Handler handler Handler
reqURI string reqURI string
expect map[string]interface{} expect map[string]any
}{ }{
{ {
reqURI: "/foo", reqURI: "/foo",
@ -25,11 +25,11 @@ func TestHandler(t *testing.T) {
Mappings: []Mapping{ Mappings: []Mapping{
{ {
Input: "/foo", Input: "/foo",
Outputs: []interface{}{"FOO"}, Outputs: []any{"FOO"},
}, },
}, },
}, },
expect: map[string]interface{}{ expect: map[string]any{
"output": "FOO", "output": "FOO",
}, },
}, },
@ -41,11 +41,11 @@ func TestHandler(t *testing.T) {
Mappings: []Mapping{ Mappings: []Mapping{
{ {
InputRegexp: "(/abc)", InputRegexp: "(/abc)",
Outputs: []interface{}{"ABC"}, Outputs: []any{"ABC"},
}, },
}, },
}, },
expect: map[string]interface{}{ expect: map[string]any{
"output": "ABC", "output": "ABC",
}, },
}, },
@ -57,11 +57,11 @@ func TestHandler(t *testing.T) {
Mappings: []Mapping{ Mappings: []Mapping{
{ {
InputRegexp: "(xyz)", InputRegexp: "(xyz)",
Outputs: []interface{}{"...${1}..."}, Outputs: []any{"...${1}..."},
}, },
}, },
}, },
expect: map[string]interface{}{ expect: map[string]any{
"output": "...xyz...", "output": "...xyz...",
}, },
}, },
@ -74,11 +74,11 @@ func TestHandler(t *testing.T) {
Mappings: []Mapping{ Mappings: []Mapping{
{ {
InputRegexp: "(?i)(\\^|`|<|>|%|\\\\|\\{|\\}|\\|)", InputRegexp: "(?i)(\\^|`|<|>|%|\\\\|\\{|\\}|\\|)",
Outputs: []interface{}{"3"}, Outputs: []any{"3"},
}, },
}, },
}, },
expect: map[string]interface{}{ expect: map[string]any{
"output": "3", "output": "3",
}, },
}, },
@ -90,11 +90,11 @@ func TestHandler(t *testing.T) {
Mappings: []Mapping{ Mappings: []Mapping{
{ {
Input: "/foo", Input: "/foo",
Outputs: []interface{}{"{testvar}"}, Outputs: []any{"{testvar}"},
}, },
}, },
}, },
expect: map[string]interface{}{ expect: map[string]any{
"output": "testing", "output": "testing",
}, },
}, },

View file

@ -1032,7 +1032,7 @@ func (m *MatchNot) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading matcher sets: %v", err) return fmt.Errorf("loading matcher sets: %v", err)
} }
for _, modMap := range matcherSets.([]map[string]interface{}) { for _, modMap := range matcherSets.([]map[string]any) {
var ms MatcherSet var ms MatcherSet
for _, modIface := range modMap { for _, modIface := range modMap {
ms = append(ms, modIface.(RequestMatcher)) ms = append(ms, modIface.(RequestMatcher))

View file

@ -807,7 +807,7 @@ func TestVarREMatcher(t *testing.T) {
req := &http.Request{URL: new(url.URL), Method: http.MethodGet} req := &http.Request{URL: new(url.URL), Method: http.MethodGet}
repl := caddy.NewReplacer() repl := caddy.NewReplacer()
ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]interface{})) ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]any))
req = req.WithContext(ctx) req = req.WithContext(ctx)
addHTTPVarsToReplacer(repl, req, httptest.NewRecorder()) addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())

View file

@ -57,7 +57,7 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
SetVar(req.Context(), "start_time", time.Now()) SetVar(req.Context(), "start_time", time.Now())
SetVar(req.Context(), "uuid", new(requestID)) SetVar(req.Context(), "uuid", new(requestID))
httpVars := func(key string) (interface{}, bool) { httpVars := func(key string) (any, bool) {
if req != nil { if req != nil {
// query string parameters // query string parameters
if strings.HasPrefix(key, reqURIQueryReplPrefix) { if strings.HasPrefix(key, reqURIQueryReplPrefix) {
@ -233,7 +233,7 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
// middleware variables // middleware variables
if strings.HasPrefix(key, varsReplPrefix) { if strings.HasPrefix(key, varsReplPrefix) {
varName := key[len(varsReplPrefix):] varName := key[len(varsReplPrefix):]
tbl := req.Context().Value(VarsCtxKey).(map[string]interface{}) tbl := req.Context().Value(VarsCtxKey).(map[string]any)
raw := tbl[varName] raw := tbl[varName]
// variables can be dynamic, so always return true // variables can be dynamic, so always return true
// even when it may not be set; treat as empty then // even when it may not be set; treat as empty then
@ -258,7 +258,7 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
repl.Map(httpVars) repl.Map(httpVars)
} }
func getReqTLSReplacement(req *http.Request, key string) (interface{}, bool) { func getReqTLSReplacement(req *http.Request, key string) (any, bool) {
if req == nil || req.TLS == nil { if req == nil || req.TLS == nil {
return nil, false return nil, false
} }
@ -279,7 +279,7 @@ func getReqTLSReplacement(req *http.Request, key string) (interface{}, bool) {
if strings.HasPrefix(field, "client.san.") { if strings.HasPrefix(field, "client.san.") {
field = field[len("client.san."):] field = field[len("client.san."):]
var fieldName string var fieldName string
var fieldValue interface{} var fieldValue any
switch { switch {
case strings.HasPrefix(field, "dns_names"): case strings.HasPrefix(field, "dns_names"):
fieldName = "dns_names" fieldName = "dns_names"
@ -383,7 +383,7 @@ func getReqTLSReplacement(req *http.Request, key string) (interface{}, bool) {
} }
// marshalPublicKey returns the byte encoding of pubKey. // marshalPublicKey returns the byte encoding of pubKey.
func marshalPublicKey(pubKey interface{}) ([]byte, error) { func marshalPublicKey(pubKey any) ([]byte, error) {
switch key := pubKey.(type) { switch key := pubKey.(type) {
case *rsa.PublicKey: case *rsa.PublicKey:
return asn1.Marshal(key) return asn1.Marshal(key)

View file

@ -76,7 +76,7 @@ func (adminUpstreams) handleUpstreams(w http.ResponseWriter, r *http.Request) er
// Iterate over the upstream pool (needs to be fast) // Iterate over the upstream pool (needs to be fast)
var rangeErr error var rangeErr error
hosts.Range(func(key, val interface{}) bool { hosts.Range(func(key, val any) bool {
address, ok := key.(string) address, ok := key.(string)
if !ok { if !ok {
rangeErr = caddy.APIError{ rangeErr = caddy.APIError{

View file

@ -269,7 +269,7 @@ func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, upstre
// attach dialing information to this request // attach dialing information to this request
ctx := h.ctx.Context ctx := h.ctx.Context
ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer()) ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer())
ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]interface{}{ ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{
dialInfoVarKey: dialInfo, dialInfoVarKey: dialInfo,
}) })
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)

View file

@ -1317,7 +1317,7 @@ func (brc bodyReadCloser) Close() error {
// bufPool is used for buffering requests and responses. // bufPool is used for buffering requests and responses.
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -279,7 +279,7 @@ func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
} }
var streamingBufPool = sync.Pool{ var streamingBufPool = sync.Pool{
New: func() interface{} { New: func() any {
// The Pool's New function should generally only return pointer // The Pool's New function should generally only return pointer
// types, since a pointer can be put into the return interface // types, since a pointer can be put into the return interface
// value without an allocation // value without an allocation

View file

@ -283,7 +283,7 @@ func buildQueryString(qs string, repl *caddy.Replacer) string {
// consume the component and write the result // consume the component and write the result
comp := qs[:end] comp := qs[:end]
comp, _ = repl.ReplaceFunc(comp, func(name string, val interface{}) (interface{}, error) { comp, _ = repl.ReplaceFunc(comp, func(name string, val any) (any, error) {
if name == "http.request.uri.query" && wroteVal { if name == "http.request.uri.query" && wroteVal {
return val, nil // already escaped return val, nil // already escaped
} }

View file

@ -151,7 +151,7 @@ func (routes RouteList) ProvisionHandlers(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("route %d: loading handler modules: %v", i, err) return fmt.Errorf("route %d: loading handler modules: %v", i, err)
} }
for _, handler := range handlersIface.([]interface{}) { for _, handler := range handlersIface.([]any) {
routes[i].Handlers = append(routes[i].Handlers, handler.(MiddlewareHandler)) routes[i].Handlers = append(routes[i].Handlers, handler.(MiddlewareHandler))
} }
@ -315,9 +315,9 @@ func (ms MatcherSets) AnyMatch(req *http.Request) bool {
return len(ms) == 0 return len(ms) == 0
} }
// FromInterface fills ms from an interface{} value obtained from LoadModule. // FromInterface fills ms from an 'any' value obtained from LoadModule.
func (ms *MatcherSets) FromInterface(matcherSets interface{}) error { func (ms *MatcherSets) FromInterface(matcherSets any) error {
for _, matcherSetIfaces := range matcherSets.([]map[string]interface{}) { for _, matcherSetIfaces := range matcherSets.([]map[string]any) {
var matcherSet MatcherSet var matcherSet MatcherSet
for _, matcher := range matcherSetIfaces { for _, matcher := range matcherSetIfaces {
reqMatcher, ok := matcher.(RequestMatcher) reqMatcher, ok := matcher.(RequestMatcher)

View file

@ -585,7 +585,7 @@ func PrepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter
// set up the context for the request // set up the context for the request
ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl) ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl)
ctx = context.WithValue(ctx, ServerCtxKey, s) ctx = context.WithValue(ctx, ServerCtxKey, s)
ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]interface{})) ctx = context.WithValue(ctx, VarsCtxKey, make(map[string]any))
ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{})) ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{}))
var url2 url.URL // avoid letting this escape to the heap var url2 url.URL // avoid letting this escape to the heap
ctx = context.WithValue(ctx, OriginalRequestCtxKey, originalRequest(r, &url2)) ctx = context.WithValue(ctx, OriginalRequestCtxKey, originalRequest(r, &url2))

View file

@ -283,7 +283,7 @@ func cmdRespond(fl caddycmd.Flags) (int, error) {
// build headers map // build headers map
hdr := make(http.Header) hdr := make(http.Header)
for i, h := range respondCmdHeaders { for i, h := range respondCmdHeaders {
key, val, found := cut(h, ":") // TODO: use strings.Cut() once Go 1.18 is our minimum key, val, found := strings.Cut(h, ":")
key, val = strings.TrimSpace(key), strings.TrimSpace(val) key, val = strings.TrimSpace(key), strings.TrimSpace(val)
if !found || key == "" || val == "" { if !found || key == "" || val == "" {
return caddy.ExitCodeFailedStartup, fmt.Errorf("header %d: invalid format \"%s\" (expecting \"Field: value\")", i, h) return caddy.ExitCodeFailedStartup, fmt.Errorf("header %d: invalid format \"%s\" (expecting \"Field: value\")", i, h)
@ -395,14 +395,6 @@ func cmdRespond(fl caddycmd.Flags) (int, error) {
select {} select {}
} }
// TODO: delete this and use strings.Cut() once Go 1.18 is our minimum
func cut(s, sep string) (before, after string, found bool) {
if i := strings.Index(s, sep); i >= 0 {
return s[:i], s[i+len(sep):], true
}
return s, "", false
}
// respondCmdHeaders holds the parsed values from repeated use of the --header flag. // respondCmdHeaders holds the parsed values from repeated use of the --header flag.
var respondCmdHeaders caddycmd.StringSlice var respondCmdHeaders caddycmd.StringSlice

View file

@ -10,7 +10,7 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
func extractFrontMatter(input string) (map[string]interface{}, string, error) { func extractFrontMatter(input string) (map[string]any, string, error) {
// get the bounds of the first non-empty line // get the bounds of the first non-empty line
var firstLineStart, firstLineEnd int var firstLineStart, firstLineEnd int
lineEmpty := true lineEmpty := true
@ -35,7 +35,7 @@ func extractFrontMatter(input string) (map[string]interface{}, string, error) {
// see what kind of front matter there is, if any // see what kind of front matter there is, if any
var closingFence []string var closingFence []string
var fmParser func([]byte) (map[string]interface{}, error) var fmParser func([]byte) (map[string]any, error)
for _, fmType := range supportedFrontMatterTypes { for _, fmType := range supportedFrontMatterTypes {
if firstLine == fmType.FenceOpen { if firstLine == fmType.FenceOpen {
closingFence = fmType.FenceClose closingFence = fmType.FenceClose
@ -77,35 +77,35 @@ func extractFrontMatter(input string) (map[string]interface{}, string, error) {
return fm, body, nil return fm, body, nil
} }
func yamlFrontMatter(input []byte) (map[string]interface{}, error) { func yamlFrontMatter(input []byte) (map[string]any, error) {
m := make(map[string]interface{}) m := make(map[string]any)
err := yaml.Unmarshal(input, &m) err := yaml.Unmarshal(input, &m)
return m, err return m, err
} }
func tomlFrontMatter(input []byte) (map[string]interface{}, error) { func tomlFrontMatter(input []byte) (map[string]any, error) {
m := make(map[string]interface{}) m := make(map[string]any)
err := toml.Unmarshal(input, &m) err := toml.Unmarshal(input, &m)
return m, err return m, err
} }
func jsonFrontMatter(input []byte) (map[string]interface{}, error) { func jsonFrontMatter(input []byte) (map[string]any, error) {
input = append([]byte{'{'}, input...) input = append([]byte{'{'}, input...)
input = append(input, '}') input = append(input, '}')
m := make(map[string]interface{}) m := make(map[string]any)
err := json.Unmarshal(input, &m) err := json.Unmarshal(input, &m)
return m, err return m, err
} }
type parsedMarkdownDoc struct { type parsedMarkdownDoc struct {
Meta map[string]interface{} `json:"meta,omitempty"` Meta map[string]any `json:"meta,omitempty"`
Body string `json:"body,omitempty"` Body string `json:"body,omitempty"`
} }
type frontMatterType struct { type frontMatterType struct {
FenceOpen string FenceOpen string
FenceClose []string FenceClose []string
ParseFunc func(input []byte) (map[string]interface{}, error) ParseFunc func(input []byte) (map[string]any, error)
} }
var supportedFrontMatterTypes = []frontMatterType{ var supportedFrontMatterTypes = []frontMatterType{

View file

@ -44,7 +44,7 @@ import (
type TemplateContext struct { type TemplateContext struct {
Root http.FileSystem Root http.FileSystem
Req *http.Request Req *http.Request
Args []interface{} // defined by arguments to funcInclude Args []any // defined by arguments to funcInclude
RespHeader WrappedHeader RespHeader WrappedHeader
CustomFuncs []template.FuncMap // functions added by plugins CustomFuncs []template.FuncMap // functions added by plugins
@ -99,7 +99,7 @@ func (c TemplateContext) OriginalReq() http.Request {
// Note that included files are NOT escaped, so you should only include // Note that included files are NOT escaped, so you should only include
// trusted files. If it is not trusted, be sure to use escaping functions // trusted files. If it is not trusted, be sure to use escaping functions
// in your template. // in your template.
func (c TemplateContext) funcInclude(filename string, args ...interface{}) (string, error) { func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) {
bodyBuf := bufPool.Get().(*bytes.Buffer) bodyBuf := bufPool.Get().(*bytes.Buffer)
bodyBuf.Reset() bodyBuf.Reset()
@ -304,7 +304,7 @@ func (TemplateContext) funcStripHTML(s string) string {
// funcMarkdown renders the markdown body as HTML. The resulting // funcMarkdown renders the markdown body as HTML. The resulting
// HTML is NOT escaped so that it can be rendered as HTML. // HTML is NOT escaped so that it can be rendered as HTML.
func (TemplateContext) funcMarkdown(input interface{}) (string, error) { func (TemplateContext) funcMarkdown(input any) (string, error) {
inputStr := toString(input) inputStr := toString(input)
md := goldmark.New( md := goldmark.New(
@ -340,7 +340,7 @@ func (TemplateContext) funcMarkdown(input interface{}) (string, error) {
// splitFrontMatter parses front matter out from the beginning of input, // splitFrontMatter parses front matter out from the beginning of input,
// and returns the separated key-value pairs and the body/content. input // and returns the separated key-value pairs and the body/content. input
// must be a "stringy" value. // must be a "stringy" value.
func (TemplateContext) funcSplitFrontMatter(input interface{}) (parsedMarkdownDoc, error) { func (TemplateContext) funcSplitFrontMatter(input any) (parsedMarkdownDoc, error) {
meta, body, err := extractFrontMatter(toString(input)) meta, body, err := extractFrontMatter(toString(input))
if err != nil { if err != nil {
return parsedMarkdownDoc{}, err return parsedMarkdownDoc{}, err
@ -465,7 +465,7 @@ func (h WrappedHeader) Del(field string) string {
return "" return ""
} }
func toString(input interface{}) string { func toString(input any) string {
switch v := input.(type) { switch v := input.(type) {
case string: case string:
return v return v
@ -479,7 +479,7 @@ func toString(input interface{}) string {
} }
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return new(bytes.Buffer) return new(bytes.Buffer)
}, },
} }

View file

@ -37,7 +37,7 @@ func init() {
// //
// The key is the variable name, and the value is the value of the // The key is the variable name, and the value is the value of the
// variable. Both the name and value may use or contain placeholders. // variable. Both the name and value may use or contain placeholders.
type VarsMiddleware map[string]interface{} type VarsMiddleware map[string]any
// CaddyModule returns the Caddy module information. // CaddyModule returns the Caddy module information.
func (VarsMiddleware) CaddyModule() caddy.ModuleInfo { func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
@ -48,7 +48,7 @@ func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
} }
func (m VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { func (m VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
vars := r.Context().Value(VarsCtxKey).(map[string]interface{}) vars := r.Context().Value(VarsCtxKey).(map[string]any)
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
for k, v := range m { for k, v := range m {
keyExpanded := repl.ReplaceAll(k, "") keyExpanded := repl.ReplaceAll(k, "")
@ -156,7 +156,7 @@ func (m VarsMatcher) Match(r *http.Request) bool {
return true return true
} }
vars := r.Context().Value(VarsCtxKey).(map[string]interface{}) vars := r.Context().Value(VarsCtxKey).(map[string]any)
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
for key, vals := range m { for key, vals := range m {
@ -250,7 +250,7 @@ func (m MatchVarsRE) Provision(ctx caddy.Context) error {
// Match returns true if r matches m. // Match returns true if r matches m.
func (m MatchVarsRE) Match(r *http.Request) bool { func (m MatchVarsRE) Match(r *http.Request) bool {
vars := r.Context().Value(VarsCtxKey).(map[string]interface{}) vars := r.Context().Value(VarsCtxKey).(map[string]any)
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
for k, rm := range m { for k, rm := range m {
var varStr string var varStr string
@ -290,8 +290,8 @@ func (m MatchVarsRE) Validate() error {
// GetVar gets a value out of the context's variable table by key. // GetVar gets a value out of the context's variable table by key.
// If the key does not exist, the return value will be nil. // If the key does not exist, the return value will be nil.
func GetVar(ctx context.Context, key string) interface{} { func GetVar(ctx context.Context, key string) any {
varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{}) varMap, ok := ctx.Value(VarsCtxKey).(map[string]any)
if !ok { if !ok {
return nil return nil
} }
@ -305,8 +305,8 @@ func GetVar(ctx context.Context, key string) interface{} {
// If the value is nil (note: non-nil interface with nil // If the value is nil (note: non-nil interface with nil
// underlying value does not count) and the key exists in // underlying value does not count) and the key exists in
// the table, the key+value will be deleted from the table. // the table, the key+value will be deleted from the table.
func SetVar(ctx context.Context, key string, value interface{}) { func SetVar(ctx context.Context, key string, value any) {
varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{}) varMap, ok := ctx.Value(VarsCtxKey).(map[string]any)
if !ok { if !ok {
return return
} }

View file

@ -73,7 +73,7 @@ type CA struct {
storage certmagic.Storage storage certmagic.Storage
root, inter *x509.Certificate root, inter *x509.Certificate
interKey interface{} // TODO: should we just store these as crypto.Signer? interKey any // TODO: should we just store these as crypto.Signer?
mu *sync.RWMutex mu *sync.RWMutex
rootCertPath string // mainly used for logging purposes if trusting rootCertPath string // mainly used for logging purposes if trusting
@ -121,7 +121,7 @@ func (ca *CA) Provision(ctx caddy.Context, id string, log *zap.Logger) error {
// load the certs and key that will be used for signing // load the certs and key that will be used for signing
var rootCert, interCert *x509.Certificate var rootCert, interCert *x509.Certificate
var rootKey, interKey interface{} var rootKey, interKey any
var err error var err error
if ca.Root != nil { if ca.Root != nil {
if ca.Root.Format == "" || ca.Root.Format == "pem_file" { if ca.Root.Format == "" || ca.Root.Format == "pem_file" {
@ -161,7 +161,7 @@ func (ca CA) RootCertificate() *x509.Certificate {
// RootKey returns the CA's root private key. Since the root key is // RootKey returns the CA's root private key. Since the root key is
// not cached in memory long-term, it needs to be loaded from storage, // not cached in memory long-term, it needs to be loaded from storage,
// which could yield an error. // which could yield an error.
func (ca CA) RootKey() (interface{}, error) { func (ca CA) RootKey() (any, error) {
_, rootKey, err := ca.loadOrGenRoot() _, rootKey, err := ca.loadOrGenRoot()
return rootKey, err return rootKey, err
} }
@ -175,7 +175,7 @@ func (ca CA) IntermediateCertificate() *x509.Certificate {
} }
// IntermediateKey returns the CA's intermediate private key. // IntermediateKey returns the CA's intermediate private key.
func (ca CA) IntermediateKey() interface{} { func (ca CA) IntermediateKey() any {
ca.mu.RLock() ca.mu.RLock()
defer ca.mu.RUnlock() defer ca.mu.RUnlock()
return ca.interKey return ca.interKey
@ -196,7 +196,7 @@ func (ca *CA) NewAuthority(authorityConfig AuthorityConfig) (*authority.Authorit
// cert/key directly, since it's unlikely to expire // cert/key directly, since it's unlikely to expire
// while Caddy is running (long lifetime) // while Caddy is running (long lifetime)
var issuerCert *x509.Certificate var issuerCert *x509.Certificate
var issuerKey interface{} var issuerKey any
issuerCert = rootCert issuerCert = rootCert
var err error var err error
issuerKey, err = ca.RootKey() issuerKey, err = ca.RootKey()
@ -239,7 +239,7 @@ func (ca *CA) NewAuthority(authorityConfig AuthorityConfig) (*authority.Authorit
return auth, nil return auth, nil
} }
func (ca CA) loadOrGenRoot() (rootCert *x509.Certificate, rootKey interface{}, err error) { func (ca CA) loadOrGenRoot() (rootCert *x509.Certificate, rootKey any, err error) {
rootCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootCert()) rootCertPEM, err := ca.storage.Load(ca.ctx, ca.storageKeyRootCert())
if err != nil { if err != nil {
if !errors.Is(err, fs.ErrNotExist) { if !errors.Is(err, fs.ErrNotExist) {
@ -273,7 +273,7 @@ func (ca CA) loadOrGenRoot() (rootCert *x509.Certificate, rootKey interface{}, e
return rootCert, rootKey, nil return rootCert, rootKey, nil
} }
func (ca CA) genRoot() (rootCert *x509.Certificate, rootKey interface{}, err error) { func (ca CA) genRoot() (rootCert *x509.Certificate, rootKey any, err error) {
repl := ca.newReplacer() repl := ca.newReplacer()
rootCert, rootKey, err = generateRoot(repl.ReplaceAll(ca.RootCommonName, "")) rootCert, rootKey, err = generateRoot(repl.ReplaceAll(ca.RootCommonName, ""))

View file

@ -22,7 +22,7 @@ import (
"github.com/smallstep/cli/crypto/x509util" "github.com/smallstep/cli/crypto/x509util"
) )
func generateRoot(commonName string) (rootCrt *x509.Certificate, privateKey interface{}, err error) { func generateRoot(commonName string) (rootCrt *x509.Certificate, privateKey any, err error) {
rootProfile, err := x509util.NewRootProfile(commonName) rootProfile, err := x509util.NewRootProfile(commonName)
if err != nil { if err != nil {
return return

View file

@ -198,7 +198,7 @@ func (ap *AutomationPolicy) Provision(tlsApp *TLS) error {
if err != nil { if err != nil {
return fmt.Errorf("loading external certificate manager modules: %v", err) return fmt.Errorf("loading external certificate manager modules: %v", err)
} }
for _, getCertVal := range vals.([]interface{}) { for _, getCertVal := range vals.([]any) {
ap.Managers = append(ap.Managers, getCertVal.(certmagic.Manager)) ap.Managers = append(ap.Managers, getCertVal.(certmagic.Manager))
} }
} }
@ -209,7 +209,7 @@ func (ap *AutomationPolicy) Provision(tlsApp *TLS) error {
if err != nil { if err != nil {
return fmt.Errorf("loading TLS automation management module: %s", err) return fmt.Errorf("loading TLS automation management module: %s", err)
} }
for _, issVal := range val.([]interface{}) { for _, issVal := range val.([]any) {
ap.Issuers = append(ap.Issuers, issVal.(certmagic.Issuer)) ap.Issuers = append(ap.Issuers, issVal.(certmagic.Issuer))
} }
} }

View file

@ -46,7 +46,7 @@ func (cp ConnectionPolicies) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading handshake matchers: %v", err) return fmt.Errorf("loading handshake matchers: %v", err)
} }
for _, modIface := range mods.(map[string]interface{}) { for _, modIface := range mods.(map[string]any) {
cp[i].matchers = append(cp[i].matchers, modIface.(ConnectionMatcher)) cp[i].matchers = append(cp[i].matchers, modIface.(ConnectionMatcher))
} }
@ -66,7 +66,7 @@ func (cp ConnectionPolicies) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading client cert verifiers: %v", err) return fmt.Errorf("loading client cert verifiers: %v", err)
} }
for _, validator := range clientCertValidations.([]interface{}) { for _, validator := range clientCertValidations.([]any) {
cp[i].ClientAuthentication.verifiers = append(cp[i].ClientAuthentication.verifiers, validator.(ClientCertificateVerifier)) cp[i].ClientAuthentication.verifiers = append(cp[i].ClientAuthentication.verifiers, validator.(ClientCertificateVerifier))
} }
} }

View file

@ -113,7 +113,7 @@ func (t *TLS) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading certificate loader modules: %s", err) return fmt.Errorf("loading certificate loader modules: %s", err)
} }
for modName, modIface := range val.(map[string]interface{}) { for modName, modIface := range val.(map[string]any) {
if modName == "automate" { if modName == "automate" {
// special case; these will be loaded in later using our automation facilities, // special case; these will be loaded in later using our automation facilities,
// which we want to avoid doing during provisioning // which we want to avoid doing during provisioning

View file

@ -89,7 +89,7 @@ func (fe *FilterEncoder) Provision(ctx caddy.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("loading log filter modules: %v", err) return fmt.Errorf("loading log filter modules: %v", err)
} }
for fieldName, modIface := range vals.(map[string]interface{}) { for fieldName, modIface := range vals.(map[string]any) {
fe.Fields[fieldName] = modIface.(LogFieldFilter) fe.Fields[fieldName] = modIface.(LogFieldFilter)
} }
@ -326,7 +326,7 @@ func (fe FilterEncoder) AddUintptr(key string, value uintptr) {
} }
// AddReflected is part of the zapcore.ObjectEncoder interface. // AddReflected is part of the zapcore.ObjectEncoder interface.
func (fe FilterEncoder) AddReflected(key string, value interface{}) error { func (fe FilterEncoder) AddReflected(key string, value any) error {
if !fe.filtered(key, value) { if !fe.filtered(key, value) {
return fe.wrapped.AddReflected(key, value) return fe.wrapped.AddReflected(key, value)
} }
@ -367,7 +367,7 @@ func (fe FilterEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (
// added to the underlying encoder (so do not do // added to the underlying encoder (so do not do
// that again). If false was returned, the field has // that again). If false was returned, the field has
// not yet been added to the underlying encoder. // not yet been added to the underlying encoder.
func (fe FilterEncoder) filtered(key string, value interface{}) bool { func (fe FilterEncoder) filtered(key string, value any) bool {
filter, ok := fe.Fields[fe.keyPrefix+key] filter, ok := fe.Fields[fe.keyPrefix+key]
if !ok { if !ok {
return false return false

View file

@ -95,7 +95,7 @@ func (nopEncoder) AddUint8(key string, value uint8) {}
func (nopEncoder) AddUintptr(key string, value uintptr) {} func (nopEncoder) AddUintptr(key string, value uintptr) {}
// AddReflected is part of the zapcore.ObjectEncoder interface. // AddReflected is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) AddReflected(key string, value interface{}) error { return nil } func (nopEncoder) AddReflected(key string, value any) error { return nil }
// OpenNamespace is part of the zapcore.ObjectEncoder interface. // OpenNamespace is part of the zapcore.ObjectEncoder interface.
func (nopEncoder) OpenNamespace(key string) {} func (nopEncoder) OpenNamespace(key string) {}

View file

@ -56,7 +56,7 @@ type zapLogger struct {
zl *zap.Logger zl *zap.Logger
} }
func (l *zapLogger) Println(v ...interface{}) { func (l *zapLogger) Println(v ...any) {
l.zl.Sugar().Error(v...) l.zl.Sugar().Error(v...)
} }

View file

@ -27,7 +27,7 @@ import (
// NewReplacer returns a new Replacer. // NewReplacer returns a new Replacer.
func NewReplacer() *Replacer { func NewReplacer() *Replacer {
rep := &Replacer{ rep := &Replacer{
static: make(map[string]interface{}), static: make(map[string]any),
} }
rep.providers = []ReplacerFunc{ rep.providers = []ReplacerFunc{
globalDefaultReplacements, globalDefaultReplacements,
@ -40,7 +40,7 @@ func NewReplacer() *Replacer {
// without the global default replacements. // without the global default replacements.
func NewEmptyReplacer() *Replacer { func NewEmptyReplacer() *Replacer {
rep := &Replacer{ rep := &Replacer{
static: make(map[string]interface{}), static: make(map[string]any),
} }
rep.providers = []ReplacerFunc{ rep.providers = []ReplacerFunc{
rep.fromStatic, rep.fromStatic,
@ -53,7 +53,7 @@ func NewEmptyReplacer() *Replacer {
// use NewReplacer to make one. // use NewReplacer to make one.
type Replacer struct { type Replacer struct {
providers []ReplacerFunc providers []ReplacerFunc
static map[string]interface{} static map[string]any
} }
// Map adds mapFunc to the list of value providers. // Map adds mapFunc to the list of value providers.
@ -63,13 +63,13 @@ func (r *Replacer) Map(mapFunc ReplacerFunc) {
} }
// Set sets a custom variable to a static value. // Set sets a custom variable to a static value.
func (r *Replacer) Set(variable string, value interface{}) { func (r *Replacer) Set(variable string, value any) {
r.static[variable] = value r.static[variable] = value
} }
// Get gets a value from the replacer. It returns // Get gets a value from the replacer. It returns
// the value and whether the variable was known. // the value and whether the variable was known.
func (r *Replacer) Get(variable string) (interface{}, bool) { func (r *Replacer) Get(variable string) (any, bool) {
for _, mapFunc := range r.providers { for _, mapFunc := range r.providers {
if val, ok := mapFunc(variable); ok { if val, ok := mapFunc(variable); ok {
return val, true return val, true
@ -92,7 +92,7 @@ func (r *Replacer) Delete(variable string) {
} }
// fromStatic provides values from r.static. // fromStatic provides values from r.static.
func (r *Replacer) fromStatic(key string) (interface{}, bool) { func (r *Replacer) fromStatic(key string) (any, bool) {
val, ok := r.static[key] val, ok := r.static[key]
return val, ok return val, ok
} }
@ -230,7 +230,7 @@ scan:
return sb.String(), nil return sb.String(), nil
} }
func toString(val interface{}) string { func toString(val any) string {
switch v := val.(type) { switch v := val.(type) {
case nil: case nil:
return "" return ""
@ -275,9 +275,9 @@ func toString(val interface{}) string {
// to service that key (even if the value is blank). If the // to service that key (even if the value is blank). If the
// function does not recognize the key, false should be // function does not recognize the key, false should be
// returned. // returned.
type ReplacerFunc func(key string) (interface{}, bool) type ReplacerFunc func(key string) (any, bool)
func globalDefaultReplacements(key string) (interface{}, bool) { func globalDefaultReplacements(key string) (any, bool) {
// check environment variable // check environment variable
const envPrefix = "env." const envPrefix = "env."
if strings.HasPrefix(key, envPrefix) { if strings.HasPrefix(key, envPrefix) {
@ -316,7 +316,7 @@ func globalDefaultReplacements(key string) (interface{}, bool) {
// will be the replacement, and returns the value that // will be the replacement, and returns the value that
// will actually be the replacement, or an error. Note // will actually be the replacement, or an error. Note
// that errors are sometimes ignored by replacers. // that errors are sometimes ignored by replacers.
type ReplacementFunc func(variable string, val interface{}) (interface{}, error) type ReplacementFunc func(variable string, val any) (any, error)
// nowFunc is a variable so tests can change it // nowFunc is a variable so tests can change it
// in order to obtain a deterministic time. // in order to obtain a deterministic time.

View file

@ -178,7 +178,7 @@ func TestReplacerSet(t *testing.T) {
for _, tc := range []struct { for _, tc := range []struct {
variable string variable string
value interface{} value any
}{ }{
{ {
variable: "test1", variable: "test1",
@ -236,7 +236,7 @@ func TestReplacerReplaceKnown(t *testing.T) {
rep := Replacer{ rep := Replacer{
providers: []ReplacerFunc{ providers: []ReplacerFunc{
// split our possible vars to two functions (to test if both functions are called) // split our possible vars to two functions (to test if both functions are called)
func(key string) (val interface{}, ok bool) { func(key string) (val any, ok bool) {
switch key { switch key {
case "test1": case "test1":
return "val1", true return "val1", true
@ -250,7 +250,7 @@ func TestReplacerReplaceKnown(t *testing.T) {
return "NOOO", false return "NOOO", false
} }
}, },
func(key string) (val interface{}, ok bool) { func(key string) (val any, ok bool) {
switch key { switch key {
case "1": case "1":
return "test-123", true return "test-123", true
@ -306,7 +306,7 @@ func TestReplacerReplaceKnown(t *testing.T) {
func TestReplacerDelete(t *testing.T) { func TestReplacerDelete(t *testing.T) {
rep := Replacer{ rep := Replacer{
static: map[string]interface{}{ static: map[string]any{
"key1": "val1", "key1": "val1",
"key2": "val2", "key2": "val2",
"key3": "val3", "key3": "val3",
@ -341,10 +341,10 @@ func TestReplacerMap(t *testing.T) {
rep := testReplacer() rep := testReplacer()
for i, tc := range []ReplacerFunc{ for i, tc := range []ReplacerFunc{
func(key string) (val interface{}, ok bool) { func(key string) (val any, ok bool) {
return "", false return "", false
}, },
func(key string) (val interface{}, ok bool) { func(key string) (val any, ok bool) {
return "", false return "", false
}, },
} { } {
@ -453,6 +453,6 @@ func BenchmarkReplacer(b *testing.B) {
func testReplacer() Replacer { func testReplacer() Replacer {
return Replacer{ return Replacer{
providers: make([]ReplacerFunc, 0), providers: make([]ReplacerFunc, 0),
static: make(map[string]interface{}), static: make(map[string]any),
} }
} }

View file

@ -57,13 +57,13 @@ import (
// NewUsagePool() to make a new one. // NewUsagePool() to make a new one.
type UsagePool struct { type UsagePool struct {
sync.RWMutex sync.RWMutex
pool map[interface{}]*usagePoolVal pool map[any]*usagePoolVal
} }
// NewUsagePool returns a new usage pool that is ready to use. // NewUsagePool returns a new usage pool that is ready to use.
func NewUsagePool() *UsagePool { func NewUsagePool() *UsagePool {
return &UsagePool{ return &UsagePool{
pool: make(map[interface{}]*usagePoolVal), pool: make(map[any]*usagePoolVal),
} }
} }
@ -74,7 +74,7 @@ func NewUsagePool() *UsagePool {
// or constructed value is returned. The loaded return value is true // or constructed value is returned. The loaded return value is true
// if the value already existed and was loaded, or false if it was // if the value already existed and was loaded, or false if it was
// newly constructed. // newly constructed.
func (up *UsagePool) LoadOrNew(key interface{}, construct Constructor) (value interface{}, loaded bool, err error) { func (up *UsagePool) LoadOrNew(key any, construct Constructor) (value any, loaded bool, err error) {
var upv *usagePoolVal var upv *usagePoolVal
up.Lock() up.Lock()
upv, loaded = up.pool[key] upv, loaded = up.pool[key]
@ -113,7 +113,7 @@ func (up *UsagePool) LoadOrNew(key interface{}, construct Constructor) (value in
// already exists, or stores it if it does not exist. It returns the // already exists, or stores it if it does not exist. It returns the
// value that was either loaded or stored, and true if the value already // value that was either loaded or stored, and true if the value already
// existed and was // existed and was
func (up *UsagePool) LoadOrStore(key, val interface{}) (value interface{}, loaded bool) { func (up *UsagePool) LoadOrStore(key, val any) (value any, loaded bool) {
var upv *usagePoolVal var upv *usagePoolVal
up.Lock() up.Lock()
upv, loaded = up.pool[key] upv, loaded = up.pool[key]
@ -144,7 +144,7 @@ func (up *UsagePool) LoadOrStore(key, val interface{}) (value interface{}, loade
// This method is somewhat naive and acquires a read lock on the // This method is somewhat naive and acquires a read lock on the
// entire pool during iteration, so do your best to make f() really // entire pool during iteration, so do your best to make f() really
// fast, m'kay? // fast, m'kay?
func (up *UsagePool) Range(f func(key, value interface{}) bool) { func (up *UsagePool) Range(f func(key, value any) bool) {
up.RLock() up.RLock()
defer up.RUnlock() defer up.RUnlock()
for key, upv := range up.pool { for key, upv := range up.pool {
@ -166,7 +166,7 @@ func (up *UsagePool) Range(f func(key, value interface{}) bool) {
// true if the usage count reached 0 and the value was deleted. // true if the usage count reached 0 and the value was deleted.
// It panics if the usage count drops below 0; always call // It panics if the usage count drops below 0; always call
// Delete precisely as many times as LoadOrStore. // Delete precisely as many times as LoadOrStore.
func (up *UsagePool) Delete(key interface{}) (deleted bool, err error) { func (up *UsagePool) Delete(key any) (deleted bool, err error) {
up.Lock() up.Lock()
upv, ok := up.pool[key] upv, ok := up.pool[key]
if !ok { if !ok {
@ -206,7 +206,7 @@ type Destructor interface {
type usagePoolVal struct { type usagePoolVal struct {
refs int32 // accessed atomically; must be 64-bit aligned for 32-bit systems refs int32 // accessed atomically; must be 64-bit aligned for 32-bit systems
value interface{} value any
err error err error
sync.RWMutex sync.RWMutex
} }