-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathhello.go
62 lines (53 loc) · 1.32 KB
/
hello.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"mime"
"net/http"
)
func init() {
// Had to do this because returns svg as text/xml when running on AppEngine: http://goo.gl/hwZSp2
mime.AddExtensionType(".svg", "image/svg+xml")
r := mux.NewRouter()
sr := r.PathPrefix("/api").Subrouter()
sr.HandleFunc("/posts", Posts)
r.HandleFunc("/{rest:.*}", handler)
http.Handle("/", r)
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("path:", r.URL.Path)
http.ServeFile(w, r, "static/"+r.URL.Path)
}
type Post struct {
Uid int `json:"uid"`
Text string `json:"text"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Favorite bool `json:"favorite"`
}
func Posts(w http.ResponseWriter, r *http.Request) {
posts := []Post{}
// you'd use a real database here
file, err := ioutil.ReadFile("posts.json")
if err != nil {
log.Println("Error reading posts.json:", err)
panic(err)
}
fmt.Printf("file: %s\n", string(file))
err = json.Unmarshal(file, &posts)
if err != nil {
log.Println("Error unmarshalling posts.json:", err)
}
bs, err := json.Marshal(posts)
if err != nil {
ReturnError(w, err)
return
}
fmt.Fprint(w, string(bs))
}
func ReturnError(w http.ResponseWriter, err error) {
fmt.Fprint(w, "{\"error\": \"%v\"}", err)
}