Created
March 3, 2015 15:49
-
-
Save yusuke024/fdfe8a680fadcc90a0a8 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" | |
| "log" | |
| "net/http" | |
| ) | |
| type Comment struct { | |
| Author string `json:"author"` | |
| Text string `json:"text"` | |
| } | |
| var ( | |
| comments = []Comment{ | |
| Comment{Author: "Pete Hunt", Text: "This is one comment"}, | |
| Comment{Author: "Jordan Walke", Text: "This is *another* comment"}, | |
| } | |
| ) | |
| func main() { | |
| http.Handle("/", http.FileServer(http.Dir("root"))) | |
| http.HandleFunc("/comments", handleComments) | |
| log.Fatal(http.ListenAndServe(":8080", nil)) | |
| } | |
| func handleComments(w http.ResponseWriter, r *http.Request) { | |
| if r.Method == "POST" { | |
| author := r.PostFormValue("author") | |
| text := r.PostFormValue("text") | |
| comments = append(comments, Comment{Author: author, Text: text}) | |
| } | |
| json, err := json.Marshal(comments) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| w.Write(json) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment