-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit.go
99 lines (82 loc) · 1.89 KB
/
edit.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package ironclad
import (
"errors"
"net/http"
"golang.org/x/net/context"
)
type SingleListing struct {
Redirect bool
Edit bool
Listing *Listing
Err error
Common
}
var AccessDenied = errors.New("access denied")
func (e SingleListing) Template() string { return "SingleListing.html" }
func (e SingleListing) NewURL() string {
if e.Redirect {
if e.Edit {
return "/edit/" + string(e.Listing.ID)
} else {
return "/view/" + string(e.Listing.ID)
}
} else {
return ""
}
}
func ViewListing(s *Subject, c context.Context, r *http.Request) (Template, error) {
listing, err := lookup(c, idFrom(r))
if err != nil || listing == nil {
return nil, err
}
return SingleListing{
Listing: listing,
Common: NewCommon(s, r),
}, nil
}
func EditListing(s *Subject, c context.Context, r *http.Request) (Template, error) {
listing, err := lookup(c, idFrom(r))
if err != nil || listing == nil {
return nil, err
}
if !s.CanEdit(listing) {
return nil, AccessDenied
}
resp := SingleListing{
Edit: true,
Listing: listing,
Common: NewCommon(s, r),
}
if r.Method == "POST" {
listing.Title = r.FormValue("title")
listing.Body = r.FormValue("body")
if err := listing.NormalizeAndValidate(); err != nil {
resp.Err = err
} else if err := persist(c, listing); err != nil {
resp.Err = err
} else {
resp.Edit = false // hide the edit form if we're done
resp.Redirect = true
}
}
return resp, nil
}
func CreateListing(s *Subject, c context.Context, r *http.Request) (Template, error) {
if !s.CanCreate() {
return nil, AccessDenied
}
listing := &Listing{
Seller: s.Subject,
Category: ParseCategory(r.FormValue("category")),
Seeking: r.FormValue("seeking") != "",
}
if err := persist(c, listing); err != nil {
return nil, err
}
return SingleListing{
Edit: true,
Redirect: true,
Listing: listing,
Common: NewCommon(s, r),
}, nil
}