Skip to content

Instantly share code, notes, and snippets.

@vonneudeck
Last active March 18, 2020 02:40
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 vonneudeck/d292338d2eca75ed23ca274f2f668c7a to your computer and use it in GitHub Desktop.
Save vonneudeck/d292338d2eca75ed23ca274f2f668c7a to your computer and use it in GitHub Desktop.
RC database server
package main
import (
"encoding/json"
"log"
"net/http"
)
var m = make(map[string]string)
type errorMessage struct {
Message string
StatusCode int
Key string
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
b, _ := json.Marshal(m)
w.Write(b)
}
func setHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if len(r.Form) != 1 {
status := 400
w.WriteHeader(status)
e := errorMessage{"Must set exactly one key per request", status, ""}
b, _ := json.Marshal(e)
w.Write(b)
} else {
for key, value := range r.Form {
if len(value) > 1 {
status := 400
w.WriteHeader(status)
e := errorMessage{"Can’t assign more than one value to a key", status, key}
b, _ := json.Marshal(e)
w.Write(b)
} else {
m[key] = value[0]
}
}
}
}
func getHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.Form.Get("key")
_, ok := m[key]
if ok == false {
status := 404
w.WriteHeader(status)
e := errorMessage{"Can’t find key", status, key}
b, _ := json.Marshal(e)
w.Write(b)
} else {
b, _ := json.Marshal(map[string]string{key: m[key]})
w.Write(b)
}
}
func main() {
http.HandleFunc("/get", getHandler)
http.HandleFunc("/set", setHandler)
http.HandleFunc("/", defaultHandler)
log.Fatal(http.ListenAndServe(":4000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment