Last active
March 18, 2020 02:40
-
-
Save vonneudeck/d292338d2eca75ed23ca274f2f668c7a to your computer and use it in GitHub Desktop.
RC database server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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