Skip to content

Instantly share code, notes, and snippets.

@onemodtwo
Last active March 28, 2016 00:39
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 onemodtwo/ba0360162fc4279ca1a0 to your computer and use it in GitHub Desktop.
Save onemodtwo/ba0360162fc4279ca1a0 to your computer and use it in GitHub Desktop.
Simple database server in Go
/* keyValue.go */
package main
import (
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
)
var validSetQuery = regexp.MustCompile("^[a-zA-Z0-9-_ ]+=[a-zA-Z0-9-_ ]+$")
var validGetQuery = regexp.MustCompile("^[a-zA-Z0-9-_ ]+$")
var pairs = map[string]string{}
// handler for setting key-value pairs
func setHandler(w http.ResponseWriter, r *http.Request) {
descapedQuery, _ := url.QueryUnescape(r.URL.RawQuery)
if validSetQuery.MatchString(descapedQuery) {
query := strings.Split(descapedQuery, "=")
pairs[query[0]] = query[1]
fmt.Fprint(w, "(", query[0], ", ", query[1], ") successfully written.")
} else {
fmt.Fprint(w, "Please enter a valid key-value pair in the form \"/set?key=value\".")
}
return
}
// handler for getting the value for a given key
func getHandler(w http.ResponseWriter, r *http.Request) {
query, _ := url.QueryUnescape(r.URL.RawQuery)
if validGetQuery.MatchString(query) {
value, ok := pairs[query]
if ok {
fmt.Fprint(w, value)
} else {
fmt.Fprint(w, "There is no matching key in the data. Please try again.")
}
} else {
fmt.Fprint(w, "Please enter a valid key for lookup in the form \"/get?key\".")
}
return
}
func main() {
http.HandleFunc("/set", setHandler)
http.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment