Last active
April 7, 2023 14:47
-
-
Save TaylorMutch/3c33091f3cb073390402388aa85a46f6 to your computer and use it in GitHub Desktop.
Golang Hashset Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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