Skip to content

Instantly share code, notes, and snippets.

@TaylorMutch
Last active April 7, 2023 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TaylorMutch/3c33091f3cb073390402388aa85a46f6 to your computer and use it in GitHub Desktop.
Save TaylorMutch/3c33091f3cb073390402388aa85a46f6 to your computer and use it in GitHub Desktop.
Golang Hashset Example
package main
import (
"crypto"
_ "crypto/sha512"
"fmt"
)
func main() {
knownApiKeys := [][]string{
{
"random-id-1",
"random-token-1",
},
{
"random-id-2",
"random-token-2",
},
}
// Build the hashset
hashset := map[string]struct{}{}
for _, k := range knownApiKeys {
hashset[string(Hash(k))] = struct{}{}
}
// Check if a key is in the hashset
testApiKeys := [][]string{
// First key should be found
{
"random-id-1",
"random-token-1",
},
// Second key should not be foun
{
"random-id-doesnotexist",
"random-token-doesnotexist",
},
}
for _, testkey := range testApiKeys {
_, ok := hashset[Hash(testkey)]
if ok {
fmt.Println("Found match!")
} else {
fmt.Println("No match found, darn")
}
}
}
func Hash(objs ...interface{}) string {
digester := crypto.SHA512.New()
for _, ob := range objs {
fmt.Fprint(digester, ob)
}
return string(digester.Sum(nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment