Skip to content

Instantly share code, notes, and snippets.

@tristanwietsma
Created February 9, 2014 20:55
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 tristanwietsma/8905811 to your computer and use it in GitHub Desktop.
Save tristanwietsma/8905811 to your computer and use it in GitHub Desktop.
Go web server with GET, POST
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))
}
@tristanwietsma
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment