Last active
August 29, 2015 14:17
-
-
Save jochasinga/0f7ecf921dd18cef6b63 to your computer and use it in GitHub Desktop.
Handler functions for blog REST API
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" | |
"fmt" | |
"net/http" | |
"io" | |
"io/ioutil" | |
"strconv" | |
"time" | |
mux "github.com/julienschmidt/httprouter" | |
) | |
func Index(w http.ResponseWriter, r *http.Request, _ mux.Params) { | |
fmt.Fprintf(w, "<h1 style=\"font-family: Helvetica;\">Hello, welcome to blog service</h1>") | |
} | |
func PostIndex(w http.ResponseWriter, r *http.Request, _ mux.Params) { | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
w.WriteHeader(http.StatusOK) | |
posts := FindAll() | |
if err := json.NewEncoder(w).Encode(posts); err != nil { | |
panic(err) | |
} | |
} | |
func PostShow(w http.ResponseWriter, r *http.Request, ps mux.Params) { | |
id, err := strconv.Atoi(ps.ByName("postId")) | |
HandleError(err) | |
post := FindPost(id) | |
if err := json.NewEncoder(w).Encode(post); err != nil { | |
panic(err) | |
} | |
} | |
func PostCreate(w http.ResponseWriter, r *http.Request, _ mux.Params) { | |
var post Post | |
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) | |
HandleError(err) | |
if err := r.Body.Close(); err != nil { | |
panic(err) | |
} | |
// Save JSON to Post struct | |
if err := json.Unmarshal(body, &post); err != nil { | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
w.WriteHeader(422) | |
if err := json.NewEncoder(w).Encode(err); err != nil { | |
panic(err) | |
} | |
} | |
CreatePost(post) | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
w.WriteHeader(http.StatusCreated) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment