forked from remind101/empire
/
domains.go
111 lines (90 loc) · 2.11 KB
/
domains.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
100
101
102
103
104
105
106
107
108
109
110
111
package heroku
import (
"fmt"
"net/http"
"github.com/bgentry/heroku-go"
"github.com/jinzhu/gorm"
"github.com/remind101/empire/empire"
"github.com/remind101/pkg/httpx"
"golang.org/x/net/context"
)
type Domain heroku.Domain
func newDomain(d *empire.Domain) *Domain {
return &Domain{
Id: d.ID,
Hostname: d.Hostname,
CreatedAt: *d.CreatedAt,
}
}
type GetDomains struct {
*empire.Empire
}
func (h *GetDomains) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
a, err := findApp(ctx, h)
if err != nil {
return err
}
d, err := h.Domains(empire.DomainsQuery{App: a})
if err != nil {
return err
}
w.WriteHeader(200)
return Encode(w, d)
}
type PostDomainsForm struct {
Hostname string `json:"hostname"`
}
type PostDomains struct {
*empire.Empire
}
func (h *PostDomains) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
a, err := findApp(ctx, h)
if err != nil {
return err
}
var form PostDomainsForm
if err := Decode(r, &form); err != nil {
return err
}
domain := &empire.Domain{
AppID: a.ID,
Hostname: form.Hostname,
}
d, err := h.DomainsCreate(domain)
if err != nil {
if err == empire.ErrDomainInUse {
return fmt.Errorf("%s is currently in use by another app.", domain.Hostname)
} else if err == empire.ErrDomainAlreadyAdded {
return fmt.Errorf("%s is already added to this app.", domain.Hostname)
}
return err
}
w.WriteHeader(201)
return Encode(w, newDomain(d))
}
type DeleteDomain struct {
*empire.Empire
}
func (h *DeleteDomain) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
a, err := findApp(ctx, h)
if err != nil {
return err
}
vars := httpx.Vars(ctx)
name := vars["hostname"]
d, err := h.DomainsFirst(empire.DomainsQuery{Hostname: &name, App: a})
if err != nil {
if err == gorm.RecordNotFound {
return &ErrorResource{
Status: http.StatusNotFound,
ID: "not_found",
Message: "Couldn't find that domain name.",
}
}
return err
}
if err = h.DomainsDestroy(d); err != nil {
return err
}
return NoContent(w)
}