Skip to content

Instantly share code, notes, and snippets.

@yusuke024
Created March 3, 2015 15:49
Show Gist options
  • Select an option

  • Save yusuke024/fdfe8a680fadcc90a0a8 to your computer and use it in GitHub Desktop.

Select an option

Save yusuke024/fdfe8a680fadcc90a0a8 to your computer and use it in GitHub Desktop.
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