Skip to content

Instantly share code, notes, and snippets.

@barthr
Created October 3, 2016 14:31
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 barthr/8c4ee5b12ebe16f46b14e97dac913471 to your computer and use it in GitHub Desktop.
Save barthr/8c4ee5b12ebe16f46b14e97dac913471 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
var items = []string{}
func main() {
port := ":8080"
router := http.NewServeMux()
router.HandleFunc("/test", postExample)
log.Printf("Started Listening on localhost%s", port)
log.Fatal(http.ListenAndServe(port, router))
}
func postExample(res http.ResponseWriter, req *http.Request) {
switch req.Method {
case "POST":
content, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil || len(content) == 0 {
res.WriteHeader(http.StatusNoContent)
return
}
// Do something with content
// here we insert them to a slice
items = append(items, string(content))
res.WriteHeader(http.StatusCreated)
res.Write([]byte("Succesfully created item!"))
case "GET":
items, _ := json.Marshal(items)
res.Write(items)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment