forked from golang-book/bootcamp-examples
/
newmovie.go
72 lines (60 loc) · 1.36 KB
/
newmovie.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
63
64
65
66
67
68
69
70
71
72
package movieinfo
import (
"io/ioutil"
"net/http"
"strings"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/search"
"google.golang.org/appengine/urlfetch"
)
func renderMarkdown(ctx context.Context, text string) (string, error) {
client := urlfetch.Client(ctx)
result, err := client.Post(
"https://api.github.com/markdown/raw",
"text/plain",
strings.NewReader(text),
)
if err != nil {
return "", err
}
defer result.Body.Close()
bs, _ := ioutil.ReadAll(result.Body)
return string(bs), nil
}
type newMovieModel struct {
CreatedID string
}
func handleNewMovie(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
model := &newMovieModel{}
if req.Method == "POST" {
title := req.FormValue("title")
summary := req.FormValue("summary")
summary, err := renderMarkdown(ctx, summary)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
index, err := search.Open("movies")
if err != nil {
http.Error(res, err.Error(), 500)
return
}
movie := &Movie{
Title: title,
Summary: search.HTML(summary),
}
id, err := index.Put(ctx, "", movie)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
model.CreatedID = id
}
err := tpl.ExecuteTemplate(res, "new-movie", model)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
}