-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
278 lines (237 loc) · 7.04 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"database/sql"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"runtime"
"strconv"
_ "github.com/lib/pq"
)
type PostgresqlCredentials struct {
Host string `json:"host"`
Username string `json:"username"`
Sslmode string `json:"sslmode"`
Password string `json:"password"`
Port int `json:"port"`
Database string `json:"name"`
}
// struct for reading env
type VCAPServices struct {
PostgreSQL []struct {
Credentials PostgresqlCredentials `json:"credentials"`
} `json:"a9s-postgresql11"`
}
type BlogPost struct {
ID int
Title string
Description string
}
// template store
var templates map[string]*template.Template
// fill template store
func initTemplates() {
if templates == nil {
templates = make(map[string]*template.Template)
}
templates["index"] = template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
templates["new"] = template.Must(template.ParseFiles("templates/new.html", "templates/base.html"))
}
func initDatabase() {
client, err := NewClient()
if err != nil {
log.Printf("Failed to create connection: %v", err)
return
}
defer client.Close()
client.Exec("CREATE TABLE posts(id SERIAL, title varchar(256), description varchar(1024))")
}
func createCredentials() (PostgresqlCredentials, error) {
// Kubernetes
if os.Getenv("VCAP_SERVICES") == "" {
host := os.Getenv("POSTGRESQL_HOST")
if len(host) < 1 {
err := fmt.Errorf("Environment variable POSTGRESQL_HOST missing.")
log.Println(err)
return PostgresqlCredentials{}, err
}
username := os.Getenv("POSTGRESQL_USERNAME")
if len(username) < 1 {
err := fmt.Errorf("Environment variable POSTGRESQL_USERNAME missing.")
log.Println(err)
return PostgresqlCredentials{}, err
}
password := os.Getenv("POSTGRESQL_PASSWORD")
if len(password) < 1 {
err := fmt.Errorf("Environment variable POSTGRESQL_PASSWORD missing.")
log.Println(err)
return PostgresqlCredentials{}, err
}
portStr := os.Getenv("POSTGRESQL_PORT")
if len(portStr) < 1 {
err := fmt.Errorf("Environment variable POSTGRESQL_PORT missing.")
log.Println(err)
return PostgresqlCredentials{}, err
}
database := os.Getenv("POSTGRESQL_DATABASE")
if len(database) < 1 {
err := fmt.Errorf("Environment variable POSTGRESQL_DATABASE missing.")
log.Println(err)
return PostgresqlCredentials{}, err
}
sslmode := os.Getenv("POSTGRESQL_SSLMODE")
if len(sslmode) < 1 {
log.Println("Environment variable POSTGRESQL_SSLMODE missing. Using default of disabled")
sslmode = "disable"
}
port, err := strconv.Atoi(portStr)
if err != nil {
log.Println(err)
return PostgresqlCredentials{}, err
}
credentials := PostgresqlCredentials{
Host: host,
Username: username,
Sslmode: sslmode,
Password: password,
Port: port,
Database: database,
}
return credentials, nil
}
// Cloud Foundry
// no new read of the env var, the reason is the receiver loop
var s VCAPServices
err := json.Unmarshal([]byte(os.Getenv("VCAP_SERVICES")), &s)
if err != nil {
log.Println(err)
return PostgresqlCredentials{}, err
}
if s.PostgreSQL[0].Credentials.Sslmode == "" {
s.PostgreSQL[0].Credentials.Sslmode = "disable"
}
return s.PostgreSQL[0].Credentials, nil
}
func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
tmpl, _ := templates[name]
err := tmpl.ExecuteTemplate(w, template, viewModel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// NewClient ...
func NewClient() (*sql.DB, error) {
credentials, err := createCredentials()
if err != nil {
return nil, err
}
connStr := "user=" + credentials.Username + " dbname=" + credentials.Database + " password=" + credentials.Password + " host=" + credentials.Host + " port=" + strconv.Itoa(credentials.Port) + " sslmode=" + credentials.Sslmode
credentials.Password = "******"
log.Printf("Connection to:\n%v\n", credentials)
client, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
return client, err
}
func clearDatabase(w http.ResponseWriter, r *http.Request) {
client, err := NewClient()
if err != nil {
log.Printf("Failed to create connection: %v", err)
return
}
defer client.Close()
client.QueryRow(`DELETE FROM posts`)
w.Write([]byte("OK"))
}
// create new Blog post
func createBlogPost(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
title := r.PostFormValue("title")
description := r.PostFormValue("description")
http.Redirect(w, r, "/", 302)
// insert key value into service
client, err := NewClient()
if err != nil {
log.Printf("Failed to create connection: %v", err)
return
}
defer client.Close()
var postID int
err = client.QueryRow(`INSERT INTO posts(title, description) VALUES('` + title + `', '` + description + `') RETURNING id`).Scan(&postID)
if err != nil {
log.Printf("Failed to create new blog post with title %v and description %v ; err = %v", title, description, err)
return
}
log.Println("Created new blog post entry with ID: " + strconv.Itoa(postID))
}
func newBlogPost(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "new", "base", nil)
}
func renderBlogPosts(w http.ResponseWriter, r *http.Request) {
blogposts := make([]BlogPost, 0)
client, err := NewClient()
if err != nil {
log.Printf("Failed to create connection: %v\n", err)
} else {
log.Printf("Collecting blog posts.\n")
// query entries
rows, err := client.Query("SELECT id, title, description FROM posts")
if err != nil {
log.Printf("Failed to fetch blog posts, err = %v\n", err)
}
defer rows.Close()
for rows.Next() {
var id int
var title string
var description string
err := rows.Scan(&id, &title, &description)
if err == nil {
blogposts = append(blogposts, BlogPost{ID: id, Title: title, Description: description})
}
}
}
defer client.Close()
renderTemplate(w, "index", "base", blogposts)
}
func deleteBlogPost(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Printf("Failed to parse Form: %v", err)
return
}
postID := r.PostFormValue("postID")
client, err := NewClient()
if err != nil {
log.Printf("Failed to create connection: %v", err)
return
}
defer client.Close()
_, err = client.Exec(`DELETE FROM posts WHERE id =` + postID + `;`)
if err != nil {
log.Printf("Failed to delete post entry with ID: %v ; err = %v", postID, err)
return
}
http.Redirect(w, r, "/", 303)
log.Printf("Deleted blog post entry with ID: %v\n", postID)
}
func main() {
log.Println(runtime.Version())
initTemplates()
initDatabase()
port := "3000"
if port = os.Getenv("PORT"); len(port) == 0 {
port = "3000"
}
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/", renderBlogPosts)
http.HandleFunc("/blog-posts/new", newBlogPost)
http.HandleFunc("/blog-posts/create", createBlogPost)
http.HandleFunc("/blog-posts/delete", deleteBlogPost)
http.HandleFunc("/clear", clearDatabase)
log.Printf("Listening on :%v\n", port)
http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
}