Skip to content

Instantly share code, notes, and snippets.

@manishrjain
Created December 10, 2022 19:19
Show Gist options
  • Save manishrjain/ce9e3f587cde790c2e53f9db6fb9002f to your computer and use it in GitHub Desktop.
Save manishrjain/ce9e3f587cde790c2e53f9db6fb9002f to your computer and use it in GitHub Desktop.
ChatGPT writing Badger Code to store API keys
package main
import (
"fmt"
"math/rand"
"net/http"
"time"
"github.com/dgraph-io/badger"
"strings"
)
const keyLength = 25 // Length of the API key
func main() {
// Open a BadgerDB database
db, err := badger.Open(badger.DefaultOptions("./badgerdb"))
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
rand.Seed(time.Now().UnixNano()) // Seed the random number generator
// Generate a new API key
key := make([]byte, keyLength)
for i := 0; i < keyLength; i++ {
key[i] = byte(rand.Intn(26) + 65) // Generate a random uppercase letter
}
// Store the API key in BadgerDB
err = db.Update(func(txn *badger.Txn) error {
err := txn.Set([]byte("api_key"), key)
return err
})
if err != nil {
fmt.Println(err)
return
}
// Expose the API key generation, verification, and removal as a HTTP service
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Get the API key from the request query string
queryKey := r.URL.Query().Get("key")
if r.URL.Query().Get("action") == "verify" {
// Check if the given key exists in BadgerDB
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("api_key"))
if err != nil {
return err
}
storedKey, err := item.Value()
if err != nil {
return err
}
if string(storedKey) == queryKey {
w.Write([]byte("Valid API key"))
} else {
w.Write([]byte("Invalid API key"))
}
return nil
})
if err != nil {
fmt.Println(err)
return
}
} else if r.URL.Query().Get("action") == "remove" {
// Remove the given key from BadgerDB
err = db.Update(func(txn *badger.Txn) error {
err := txn.Delete([]byte("api_key"))
return err
})
if err != nil {
fmt.Println(err)
return
}
w.Write([]byte("API key removed"))
} else {
w.Write([]byte("Invalid action"))
}
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment