53 lines
2.1 KiB
Go
53 lines
2.1 KiB
Go
package guardianextension
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"os"
|
|
|
|
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
|
"github.com/twmb/murmur3"
|
|
)
|
|
|
|
// LoadData loads the map from a JSON file.
|
|
func (handler *GuardianCacheHandler) LoadData() error {
|
|
file, err := os.Open(handler.DataFile)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
decoder := json.NewDecoder(file)
|
|
return decoder.Decode(&handler.data)
|
|
}
|
|
|
|
// parseCaddyfile creates a new GuardianCacheHandler instance and initializes it by parsing the Caddyfile configuration.
|
|
// This function is used by Caddy to load the GuardianCacheHandler module from the Caddyfile. It's called once during init.
|
|
func parseCaddyfile(helper httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
|
|
handler := new(GuardianCacheHandler)
|
|
err := handler.UnmarshalCaddyfile(helper.Dispenser)
|
|
return handler, err
|
|
}
|
|
|
|
// questionHash generates a 32-byte hash string from the provided question string using the MurmurHash3 algorithm.
|
|
// The hash is encoded as a hexadecimal string and returned.
|
|
//
|
|
// Benchmarks
|
|
// cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
|
|
// BenchmarkStringSum128WithPreGeneratedData-12 6135975 179.3 ns/op
|
|
// BenchmarkSprintfWithPreGeneratedData-12 6602058 179.9 ns/op
|
|
// BenchmarkStrconvWithPreGeneratedData-12 10127676 123.0 ns/op
|
|
// BenchmarkBytesBufferWithPreGeneratedData-12 7616581 156.3 ns/op
|
|
// BenchmarkEncodingHexWithPreGeneratedData-12 18349746 64.95 ns/op <----
|
|
func questionHash(question string) string {
|
|
h1, h2 := murmur3.StringSum128(question)
|
|
hash := hex.EncodeToString([]byte{
|
|
byte(h1 >> 56), byte(h1 >> 48), byte(h1 >> 40), byte(h1 >> 32),
|
|
byte(h1 >> 24), byte(h1 >> 16), byte(h1 >> 8), byte(h1),
|
|
byte(h2 >> 56), byte(h2 >> 48), byte(h2 >> 40), byte(h2 >> 32),
|
|
byte(h2 >> 24), byte(h2 >> 16), byte(h2 >> 8), byte(h2),
|
|
})
|
|
// caddy.Log().Named("guardianextension").Sugar().Debugf("questionHash: %s -> %s", question, hash)
|
|
return hash
|
|
}
|