Created
October 3, 2016 14:31
-
-
Save barthr/8c4ee5b12ebe16f46b14e97dac913471 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"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