refactor: use maps.Copy for cleaner map handling (#6283)

Signed-off-by: gopherorg <gopherworld@icloud.com>
This commit is contained in:
gopherorg 2025-07-12 05:20:47 +08:00 committed by GitHub
parent a13ea39461
commit 1079498182
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 40 additions and 75 deletions

View File

@ -2,6 +2,7 @@ package openapi
import ( import (
"fmt" "fmt"
"maps"
"slices" "slices"
"github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3"
@ -162,9 +163,7 @@ func openAPIExample(schema *openapi3.Schema, cache map[*openapi3.Schema]*cachedS
return nil, ErrNoExample return nil, ErrNoExample
} }
for k, v := range value { maps.Copy(example, value)
example[k] = v
}
} }
return example, nil return example, nil
} }

View File

@ -2,6 +2,7 @@ package gojs
import ( import (
"context" "context"
"maps"
"reflect" "reflect"
"sync" "sync"
@ -103,9 +104,7 @@ func wrapModuleFunc(runtime *goja.Runtime, fn interface{}) interface{} {
} }
func (p *GojaModule) Set(objects Objects) Module { func (p *GojaModule) Set(objects Objects) Module {
for k, v := range objects { maps.Copy(p.sets, objects)
p.sets[k] = v
}
return p return p
} }

View File

@ -2,6 +2,7 @@ package operators
import ( import (
"fmt" "fmt"
"maps"
"strconv" "strconv"
"strings" "strings"
@ -218,9 +219,7 @@ func (r *Result) Merge(result *Result) {
r.DynamicValues[k] = sliceutil.Dedupe(append(r.DynamicValues[k], v...)) r.DynamicValues[k] = sliceutil.Dedupe(append(r.DynamicValues[k], v...))
} }
} }
for k, v := range result.PayloadValues { maps.Copy(r.PayloadValues, result.PayloadValues)
r.PayloadValues[k] = v
}
} }
// MatchFunc performs matching operation for a matcher on model and returns true or false. // MatchFunc performs matching operation for a matcher on model and returns true or false.

View File

@ -6,6 +6,7 @@ import (
"encoding/gob" "encoding/gob"
"encoding/hex" "encoding/hex"
"io" "io"
"maps"
"net/http" "net/http"
) )
@ -85,9 +86,7 @@ func toInternalResponse(resp *http.Response, body []byte) *InternalResponse {
intResp.HTTPMinor = resp.ProtoMinor intResp.HTTPMinor = resp.ProtoMinor
intResp.StatusCode = resp.StatusCode intResp.StatusCode = resp.StatusCode
intResp.StatusReason = resp.Status intResp.StatusReason = resp.Status
for k, v := range resp.Header { maps.Copy(intResp.Headers, resp.Header)
intResp.Headers[k] = v
}
intResp.Body = body intResp.Body = body
return intResp return intResp
} }

View File

@ -4,6 +4,7 @@ package generators
import ( import (
"github.com/pkg/errors" "github.com/pkg/errors"
"maps"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog" "github.com/projectdiscovery/nuclei/v3/pkg/catalog"
"github.com/projectdiscovery/nuclei/v3/pkg/types" "github.com/projectdiscovery/nuclei/v3/pkg/types"
@ -32,9 +33,7 @@ func New(payloads map[string]interface{}, attackType AttackType, templatePath st
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not parse payloads with aggression") return nil, errors.Wrap(err, "could not parse payloads with aggression")
} }
for k, v := range values { maps.Copy(payloadsFinal, values)
payloadsFinal[k] = v
}
default: default:
payloadsFinal[payloadName] = v payloadsFinal[payloadName] = v
} }

View File

@ -1,6 +1,7 @@
package generators package generators
import ( import (
maps0 "maps"
"reflect" "reflect"
) )
@ -47,9 +48,7 @@ func MergeMapsMany(maps ...interface{}) map[string][]string {
func MergeMaps(maps ...map[string]interface{}) map[string]interface{} { func MergeMaps(maps ...map[string]interface{}) map[string]interface{} {
merged := make(map[string]interface{}) merged := make(map[string]interface{})
for _, m := range maps { for _, m := range maps {
for k, v := range m { maps0.Copy(merged, m)
merged[k] = v
}
} }
return merged return merged
} }

View File

@ -3,6 +3,7 @@ package dns
import ( import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
maps0 "maps"
"strings" "strings"
"sync" "sync"
@ -181,12 +182,8 @@ func (request *Request) execute(input *contextargs.Context, domain string, metad
// expose response variables in proto_var format // expose response variables in proto_var format
// this is no-op if the template is not a multi protocol template // this is no-op if the template is not a multi protocol template
request.options.AddTemplateVars(input.MetaInput, request.Type(), request.ID, outputEvent) request.options.AddTemplateVars(input.MetaInput, request.Type(), request.ID, outputEvent)
for k, v := range previous { maps0.Copy(outputEvent, previous)
outputEvent[k] = v maps0.Copy(outputEvent, vars)
}
for k, v := range vars {
outputEvent[k] = v
}
// add variables from template context before matching/extraction // add variables from template context before matching/extraction
if request.options.HasTemplateCtx(input.MetaInput) { if request.options.HasTemplateCtx(input.MetaInput) {
outputEvent = generators.MergeMaps(outputEvent, request.options.GetTemplateCtx(input.MetaInput).GetAll()) outputEvent = generators.MergeMaps(outputEvent, request.options.GetTemplateCtx(input.MetaInput).GetAll())

View File

@ -6,6 +6,7 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"maps"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -276,9 +277,7 @@ func (request *Request) findMatchesWithReader(reader io.Reader, input *contextar
gologger.Verbose().Msgf("[%s] Processing file %s chunk %s/%s", request.options.TemplateID, filePath, processedBytes, totalBytesString) gologger.Verbose().Msgf("[%s] Processing file %s chunk %s/%s", request.options.TemplateID, filePath, processedBytes, totalBytesString)
dslMap := request.responseToDSLMap(lineContent, input.MetaInput.Input, filePath) dslMap := request.responseToDSLMap(lineContent, input.MetaInput.Input, filePath)
for k, v := range previous { maps.Copy(dslMap, previous)
dslMap[k] = v
}
// add vars to template context // add vars to template context
request.options.AddTemplateVars(input.MetaInput, request.Type(), request.ID, dslMap) request.options.AddTemplateVars(input.MetaInput, request.Type(), request.ID, dslMap)
// add template context variables to DSL map // add template context variables to DSL map
@ -347,9 +346,7 @@ func (request *Request) buildEvent(input, filePath string, fileMatches []FileMat
exprLines := make(map[string][]int) exprLines := make(map[string][]int)
exprBytes := make(map[string][]int) exprBytes := make(map[string][]int)
internalEvent := request.responseToDSLMap("", input, filePath) internalEvent := request.responseToDSLMap("", input, filePath)
for k, v := range previous { maps.Copy(internalEvent, previous)
internalEvent[k] = v
}
for _, fileMatch := range fileMatches { for _, fileMatch := range fileMatches {
exprLines[fileMatch.Expr] = append(exprLines[fileMatch.Expr], fileMatch.Line) exprLines[fileMatch.Expr] = append(exprLines[fileMatch.Expr], fileMatch.Line)
exprBytes[fileMatch.Expr] = append(exprBytes[fileMatch.Expr], fileMatch.ByteIndex) exprBytes[fileMatch.Expr] = append(exprBytes[fileMatch.Expr], fileMatch.ByteIndex)

View File

@ -1,6 +1,7 @@
package http package http
import ( import (
"maps"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -108,9 +109,7 @@ func (request *Request) getMatchPart(part string, data output.InternalEvent) (st
// responseToDSLMap converts an HTTP response to a map for use in DSL matching // responseToDSLMap converts an HTTP response to a map for use in DSL matching
func (request *Request) responseToDSLMap(resp *http.Response, host, matched, rawReq, rawResp, body, headers string, duration time.Duration, extra map[string]interface{}) output.InternalEvent { func (request *Request) responseToDSLMap(resp *http.Response, host, matched, rawReq, rawResp, body, headers string, duration time.Duration, extra map[string]interface{}) output.InternalEvent {
data := make(output.InternalEvent, 12+len(extra)+len(resp.Header)+len(resp.Cookies())) data := make(output.InternalEvent, 12+len(extra)+len(resp.Header)+len(resp.Cookies()))
for k, v := range extra { maps.Copy(data, extra)
data[k] = v
}
for _, cookie := range resp.Cookies() { for _, cookie := range resp.Cookies() {
request.setHashOrDefault(data, strings.ToLower(cookie.Name), cookie.Value) request.setHashOrDefault(data, strings.ToLower(cookie.Name), cookie.Value)
} }

View File

@ -6,6 +6,7 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"maps"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@ -974,12 +975,8 @@ func (request *Request) executeRequest(input *contextargs.Context, generatedRequ
if request.options.Interactsh != nil { if request.options.Interactsh != nil {
request.options.Interactsh.MakePlaceholders(generatedRequest.interactshURLs, outputEvent) request.options.Interactsh.MakePlaceholders(generatedRequest.interactshURLs, outputEvent)
} }
for k, v := range previousEvent { maps.Copy(finalEvent, previousEvent)
finalEvent[k] = v maps.Copy(finalEvent, outputEvent)
}
for k, v := range outputEvent {
finalEvent[k] = v
}
// Add to history the current request number metadata if asked by the user. // Add to history the current request number metadata if asked by the user.
if request.NeedsRequestCondition() { if request.NeedsRequestCondition() {

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"maps"
"net" "net"
"strings" "strings"
"sync/atomic" "sync/atomic"
@ -304,9 +305,7 @@ func (request *Request) ExecuteWithResults(target *contextargs.Context, dynamicV
templateCtx := request.options.GetTemplateCtx(input.MetaInput) templateCtx := request.options.GetTemplateCtx(input.MetaInput)
payloadValues := generators.BuildPayloadFromOptions(request.options.Options) payloadValues := generators.BuildPayloadFromOptions(request.options.Options)
for k, v := range dynamicValues { maps.Copy(payloadValues, dynamicValues)
payloadValues[k] = v
}
payloadValues["Hostname"] = hostPort payloadValues["Hostname"] = hostPort
payloadValues["Host"] = hostname payloadValues["Host"] = hostname
@ -620,9 +619,7 @@ func (request *Request) generateEventData(input *contextargs.Context, values map
} }
data := make(map[string]interface{}) data := make(map[string]interface{})
for k, v := range values { maps.Copy(data, values)
data[k] = v
}
data["type"] = request.Type().String() data["type"] = request.Type().String()
data["request-pre-condition"] = beautifyJavascript(request.PreCondition) data["request-pre-condition"] = beautifyJavascript(request.PreCondition)
data["request"] = beautifyJavascript(request.Code) data["request"] = beautifyJavascript(request.Code)

View File

@ -3,6 +3,7 @@ package network
import ( import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
maps0 "maps"
"net" "net"
"net/url" "net/url"
"os" "os"
@ -375,9 +376,7 @@ func (request *Request) executeRequestWithPayloads(variables map[string]interfac
// Run any internal extractors for the request here and add found values to map. // Run any internal extractors for the request here and add found values to map.
if request.CompiledOperators != nil { if request.CompiledOperators != nil {
values := request.CompiledOperators.ExecuteInternalExtractors(map[string]interface{}{input.Name: bufferStr}, request.Extract) values := request.CompiledOperators.ExecuteInternalExtractors(map[string]interface{}{input.Name: bufferStr}, request.Extract)
for k, v := range values { maps0.Copy(payloads, values)
payloads[k] = v
}
} }
} }
} }
@ -427,15 +426,9 @@ func (request *Request) executeRequestWithPayloads(variables map[string]interfac
if request.options.StopAtFirstMatch { if request.options.StopAtFirstMatch {
outputEvent["stop-at-first-match"] = true outputEvent["stop-at-first-match"] = true
} }
for k, v := range previous { maps0.Copy(outputEvent, previous)
outputEvent[k] = v maps0.Copy(outputEvent, interimValues)
} maps0.Copy(outputEvent, inputEvents)
for k, v := range interimValues {
outputEvent[k] = v
}
for k, v := range inputEvents {
outputEvent[k] = v
}
if request.options.Interactsh != nil { if request.options.Interactsh != nil {
request.options.Interactsh.MakePlaceholders(interactshURLs, outputEvent) request.options.Interactsh.MakePlaceholders(interactshURLs, outputEvent)
} }

View File

@ -1,6 +1,7 @@
package offlinehttp package offlinehttp
import ( import (
"maps"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -103,9 +104,7 @@ func getMatchPart(part string, data output.InternalEvent) (string, bool) {
// responseToDSLMap converts an HTTP response to a map for use in DSL matching // responseToDSLMap converts an HTTP response to a map for use in DSL matching
func (request *Request) responseToDSLMap(resp *http.Response, host, matched, rawReq, rawResp, body, headers string, duration time.Duration, extra map[string]interface{}) output.InternalEvent { func (request *Request) responseToDSLMap(resp *http.Response, host, matched, rawReq, rawResp, body, headers string, duration time.Duration, extra map[string]interface{}) output.InternalEvent {
data := make(output.InternalEvent, 12+len(extra)+len(resp.Header)+len(resp.Cookies())) data := make(output.InternalEvent, 12+len(extra)+len(resp.Header)+len(resp.Cookies()))
for k, v := range extra { maps.Copy(data, extra)
data[k] = v
}
for _, cookie := range resp.Cookies() { for _, cookie := range resp.Cookies() {
data[strings.ToLower(cookie.Name)] = cookie.Value data[strings.ToLower(cookie.Name)] = cookie.Value
} }

View File

@ -2,6 +2,7 @@ package ssl
import ( import (
"fmt" "fmt"
"maps"
"net" "net"
"strings" "strings"
"time" "time"
@ -206,9 +207,7 @@ func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicVa
requestOptions := request.options requestOptions := request.options
payloadValues := generators.BuildPayloadFromOptions(request.options.Options) payloadValues := generators.BuildPayloadFromOptions(request.options.Options)
for k, v := range dynamicValues { maps.Copy(payloadValues, dynamicValues)
payloadValues[k] = v
}
payloadValues["Hostname"] = hostPort payloadValues["Hostname"] = hostPort
payloadValues["Host"] = hostname payloadValues["Host"] = hostname
@ -271,9 +270,7 @@ func (request *Request) ExecuteWithResults(input *contextargs.Context, dynamicVa
jsonDataString := string(jsonData) jsonDataString := string(jsonData)
data := make(map[string]interface{}) data := make(map[string]interface{})
for k, v := range payloadValues { maps.Copy(data, payloadValues)
data[k] = v
}
data["type"] = request.Type().String() data["type"] = request.Type().String()
data["response"] = jsonDataString data["response"] = jsonDataString
data["host"] = input.MetaInput.Input data["host"] = input.MetaInput.Input

View File

@ -4,6 +4,7 @@ import (
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io" "io"
"maps"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -274,12 +275,8 @@ func (request *Request) executeRequestWithPayloads(target *contextargs.Context,
request.options.AddTemplateVars(target.MetaInput, request.Type(), request.ID, data) request.options.AddTemplateVars(target.MetaInput, request.Type(), request.ID, data)
data = generators.MergeMaps(data, request.options.GetTemplateCtx(target.MetaInput).GetAll()) data = generators.MergeMaps(data, request.options.GetTemplateCtx(target.MetaInput).GetAll())
for k, v := range previous { maps.Copy(data, previous)
data[k] = v maps.Copy(data, events)
}
for k, v := range events {
data[k] = v
}
event := eventcreator.CreateEventWithAdditionalOptions(request, data, requestOptions.Options.Debug || requestOptions.Options.DebugResponse, func(internalWrappedEvent *output.InternalWrappedEvent) { event := eventcreator.CreateEventWithAdditionalOptions(request, data, requestOptions.Options.Debug || requestOptions.Options.DebugResponse, func(internalWrappedEvent *output.InternalWrappedEvent) {
internalWrappedEvent.OperatorsResult.PayloadValues = payloadValues internalWrappedEvent.OperatorsResult.PayloadValues = payloadValues
@ -337,9 +334,7 @@ func (request *Request) readWriteInputWebsocket(conn net.Conn, payloadValues map
// Run any internal extractors for the request here and add found values to map. // Run any internal extractors for the request here and add found values to map.
if request.CompiledOperators != nil { if request.CompiledOperators != nil {
values := request.CompiledOperators.ExecuteInternalExtractors(map[string]interface{}{req.Name: bufferStr}, protocols.MakeDefaultExtractFunc) values := request.CompiledOperators.ExecuteInternalExtractors(map[string]interface{}{req.Name: bufferStr}, protocols.MakeDefaultExtractFunc)
for k, v := range values { maps.Copy(inputEvents, values)
inputEvents[k] = v
}
} }
} }
} }