Skip to content

Instantly share code, notes, and snippets.

@quercy
Created April 28, 2020 14:03
Show Gist options
  • Save quercy/71b5300776f0e6668ac23ed97548b677 to your computer and use it in GitHub Desktop.
Save quercy/71b5300776f0e6668ac23ed97548b677 to your computer and use it in GitHub Desktop.
RC Pairing Interview sample (in-memory db)
package main
import (
"io"
"log"
"net/http"
)
type kvBackend interface {
addKey(string, string) bool
delKey(string) bool
getKey(string) string
}
type kvBackendMemory struct {
backend map[string]string
}
func (b kvBackendMemory) addKey(k string, v string) bool {
b.backend[k] = v
return true
}
func (b kvBackendMemory) delKey(k string) bool {
return true
}
func (b kvBackendMemory) getKey(k string) string {
return b.backend[k]
}
func handleSet(key string, value string, kvStore kvBackend) bool {
success := kvStore.addKey(string(key), string(value))
return !success
}
func handleGet(key string, kvStore kvBackend) string {
res := kvStore.getKey(key)
if res != "" {
return res
}
return "No such key."
}
func main() {
var kvStore = kvBackendMemory{make(map[string]string)}
setHandler := func(w http.ResponseWriter, req *http.Request) {
msg := "There was an internal error setting that key=>value pair."
values := req.URL.Query()
if len(values) != 1 {
msg = "You must set one and only one key=>value pair."
} else {
for k, v := range values {
err := handleSet(k, v[0], kvStore)
if !err {
msg = "Successfully set that key=>value pair."
}
}
}
io.WriteString(w, msg)
}
getHandler := func(w http.ResponseWriter, req *http.Request) {
msg := "There was an internal error getting that key=>value pair."
values := req.URL.Query()
searchKey, err := values["key"]
if !err || len(values) < 1 || len(searchKey) != 1 {
msg = "Query using the form ?key=searchvalue."
} else {
msg = handleGet(searchKey[0], kvStore)
}
io.WriteString(w, msg)
}
http.HandleFunc("/set", setHandler)
http.HandleFunc("/get", getHandler)
log.Fatal(http.ListenAndServe(":4000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment