Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Created November 9, 2016 20:37
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 jochasinga/3ca7b84ab46f352d19c0d9ff5038cb9e to your computer and use it in GitHub Desktop.
Save jochasinga/3ca7b84ab46f352d19c0d9ff5038cb9e to your computer and use it in GitHub Desktop.
Database server in Go that uses url.Value as temporary key-value store and path parameter + query string to set and get data.
/* Database server */
package main
import (
"fmt"
"html"
"log"
"net/http"
"net/url"
)
// Temporary data store
var db = url.Values{}
// urlHandler parses the request URL for path and query string, then decide whether to set or get data.
func urlHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
method := html.EscapeString(r.URL.Path[1:])
current := r.URL.Query()
switch method {
case "set":
for key, vals := range current {
log.Printf("Setting %q: %q", key, vals[0])
db.Set(key, vals[0])
}
case "get":
for key, kvs := range current {
if key == "key" {
first := db.Get(kvs[0])
log.Printf("Getting %q: %q", kvs[0], first)
r.Header.Add(kvs[0], first)
}
}
}
// Call the next middleware
next.ServeHTTP(w, r)
})
}
// writeData invoke on a "get" operation and print the data stored at a given key to the browser.
func writeData(w http.ResponseWriter, r *http.Request) {
current := r.URL.Query()
for k, kv := range(current) {
if k == "key" {
fmt.Fprintf(w, r.Header.Get(kv[0]))
}
}
}
func main() {
webWriter := http.HandlerFunc(writeData)
http.Handle("/", urlHandler(webWriter))
// Run server at port 4000
log.Fatal(http.ListenAndServe(":4000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment