nuclei/pkg/utils/utils.go

74 lines
1.7 KiB
Go
Raw Permalink Normal View History

package utils
import (
2021-10-30 13:46:07 +03:00
"errors"
"fmt"
"io"
"net/url"
"strings"
"github.com/cespare/xxhash"
"github.com/projectdiscovery/nuclei/v3/pkg/catalog"
2023-03-02 14:54:01 +01:00
"github.com/projectdiscovery/retryablehttp-go"
mapsutil "github.com/projectdiscovery/utils/maps"
"golang.org/x/exp/constraints"
)
func IsBlank(value string) bool {
return strings.TrimSpace(value) == ""
}
2021-10-30 13:46:07 +03:00
func UnwrapError(err error) error {
for { // get the last wrapped error
unwrapped := errors.Unwrap(err)
if unwrapped == nil {
break
}
err = unwrapped
}
return err
}
// IsURL tests a string to determine if it is a well-structured url or not.
func IsURL(input string) bool {
u, err := url.Parse(input)
return err == nil && u.Scheme != "" && u.Host != ""
}
// ReaderFromPathOrURL reads and returns the contents of a file or url.
2024-03-13 21:02:36 +01:00
func ReaderFromPathOrURL(templatePath string, catalog catalog.Catalog) (io.ReadCloser, error) {
if IsURL(templatePath) {
2023-03-02 14:54:01 +01:00
resp, err := retryablehttp.DefaultClient().Get(templatePath)
if err != nil {
return nil, err
}
2024-03-13 21:02:36 +01:00
return resp.Body, nil
} else {
f, err := catalog.OpenFile(templatePath)
if err != nil {
return nil, err
}
2024-03-13 21:02:36 +01:00
return f, nil
}
}
// StringSliceContains checks if a string slice contains a string.
func StringSliceContains(slice []string, item string) bool {
for _, i := range slice {
if strings.EqualFold(i, item) {
return true
}
}
return false
}
// MapHash generates a hash for any give map
func MapHash[K constraints.Ordered, V any](m map[K]V) uint64 {
keys := mapsutil.GetSortedKeys(m)
var sb strings.Builder
for _, k := range keys {
sb.WriteString(fmt.Sprintf("%v:%v\n", k, m[k]))
}
return xxhash.Sum64([]byte(sb.String()))
}