Skip to content

Instantly share code, notes, and snippets.

@vonneudeck

vonneudeck/main.go

Last active Mar 18, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.