Created
February 9, 2014 20:55
-
-
Save tristanwietsma/8905811 to your computer and use it in GitHub Desktop.
Go web server with GET, POST
This file contains 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 ( | |
"fmt" | |
"github.com/gorilla/mux" | |
"github.com/tristanwietsma/metastore" | |
"log" | |
"net/http" | |
) | |
var Store metastore.MetaStore | |
func GetHandler(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
w.Header().Add("Content-Type", "text/html") | |
key := vars["key"] | |
val, ok := Store.Get(key) | |
if ok { | |
fmt.Fprintf(w, "'%s' -> '%s'\n", key, val) | |
} else { | |
fmt.Fprintf(w, "No key '%s' exists\n", key) | |
} | |
} | |
func SetHandler(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
r.ParseForm() | |
key := vars["key"] | |
Store.Set(key, r.PostFormValue("value")) | |
val, _ := Store.Get(key) | |
fmt.Fprintf(w, "'%s' has been set to '%s'\n", key, val) | |
} | |
func main() { | |
Store.Init(1000) | |
router := mux.NewRouter() | |
router.HandleFunc("/get/{key}", GetHandler).Methods("GET") | |
router.HandleFunc("/set/{key}", SetHandler).Methods("POST") | |
http.Handle("/", router) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
curl -d "value=testing" http://localhost:8080/set/123
curl http://localhost:8080/get/123