Skip to content

Instantly share code, notes, and snippets.

@benmuth
Last active June 8, 2022 22:40
Show Gist options
  • Save benmuth/80d41264420af82ac07afddb9220da74 to your computer and use it in GitHub Desktop.
Save benmuth/80d41264420af82ac07afddb9220da74 to your computer and use it in GitHub Desktop.
A database server made for the Recurse Center's pairing interview.
//Before your interview, write a program that runs a server that is accessible on http://localhost:4000/.
//When your server receives a request on http://localhost:4000/set?somekey=somevalue it should store the
//passed key and value in memory. When it receives a request on http://localhost:4000/get?key=somekey it
//should return the value stored at somekey.
//During your interview, you will pair on saving the data to a file. You can start with simply appending
//each write to the file, and work on making it more efficient if you have time.
package main
import (
"fmt"
"log"
"net/http"
)
//setHandler handles the "/set" pattern by storing the key-value pair given in the URL query string in a map.
func setHandler(w http.ResponseWriter, r *http.Request, m map[string]string) {
fmt.Printf("Set query: %v\n", r.URL.RawQuery)
for k, v := range r.URL.Query() {
m[k] = v[0]
fmt.Fprintf(w, "Key/value pair stored!\n %v = %v\n", k, v[0])
}
}
//getHandler handles the "/get" pattern by printing the value corresponding to "key" in the URL query string.
func getHandler(w http.ResponseWriter, r *http.Request, m map[string]string) {
fmt.Printf("Get query: %v\n", r.URL.RawQuery)
for _, k := range r.URL.Query()["key"] {
fmt.Fprintf(w, "<h1> Key: %s Value: %s </h1>\n", k, m[k])
fmt.Printf("Value: %s\n", m[k])
}
}
//makeHandler wraps a handler function with a map as an argument and returns a function of type http.HandlerFunc
//that can be passed to http.HandleFunc.
func makeHandler(fn func(http.ResponseWriter, *http.Request, map[string]string), m map[string]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fn(w, r, m)
}
}
func main() {
m := map[string]string{
"apple": "red",
"banana": "yellow",
"lime": "green",
}
http.HandleFunc("/set", makeHandler(setHandler, m))
http.HandleFunc("/get", makeHandler(getHandler, m))
fmt.Println("Serving . . .")
log.Fatal(http.ListenAndServe(":4000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment