-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
main.go
186 lines (154 loc) · 3.86 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
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/x/errors"
"github.com/kataras/iris/v12/x/sqlx"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "admin!123"
dbname = "test"
)
func main() {
app := iris.New()
db := mustConnectDB()
mustCreateExtensions(context.Background(), db)
mustCreateTables(context.Background(), db)
app.Post("/", insert(db))
app.Get("/", list(db))
app.Get("/{event_id:uuid}", getByID(db))
/*
curl --location --request POST 'http://localhost:8080' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "second_test_event",
"data": {
"key": "value",
"year": 2022
}
}'
curl --location --request GET 'http://localhost:8080'
curl --location --request GET 'http://localhost:8080/4fc0363f-1d1f-4a43-8608-5ed266485645'
*/
app.Listen(":8080")
}
func mustConnectDB() *sql.DB {
connString := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", connString)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
return db
}
func mustCreateExtensions(ctx context.Context, db *sql.DB) {
query := `CREATE EXTENSION IF NOT EXISTS pgcrypto;`
_, err := db.ExecContext(ctx, query)
if err != nil {
panic(err)
}
}
func mustCreateTables(ctx context.Context, db *sql.DB) {
query := `CREATE TABLE IF NOT EXISTS "events" (
"id" uuid PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
"created_at" timestamp(6) DEFAULT now(),
"name" text COLLATE "pg_catalog"."default",
"data" jsonb
);`
_, err := db.ExecContext(ctx, query)
if err != nil {
panic(err)
}
sqlx.Register("events", Event{})
}
type Event struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
Data json.RawMessage `json:"data"`
Presenter string `db:"-" json:"-"`
}
func insertEvent(ctx context.Context, db *sql.DB, evt Event) (id string, err error) {
query := `INSERT INTO events(name,data) VALUES($1,$2) RETURNING id;`
err = db.QueryRowContext(ctx, query, evt.Name, evt.Data).Scan(&id)
return
}
func listEvents(ctx context.Context, db *sql.DB) ([]Event, error) {
list := make([]Event, 0)
query := `SELECT * FROM events ORDER BY created_at;`
rows, err := db.QueryContext(ctx, query)
if err != nil {
return nil, err
}
// Not required. See sqlx.DefaultSchema.AutoCloseRows field.
// defer rows.Close()
if err = sqlx.Bind(&list, rows); err != nil {
return nil, err
}
return list, nil
}
func getEvent(ctx context.Context, db *sql.DB, id string) (evt Event, err error) {
query := `SELECT * FROM events WHERE id = $1 LIMIT 1;`
err = sqlx.Query(ctx, db, &evt, query, id)
return
//
// Same as:
//
// rows, err := db.QueryContext(ctx, query, id)
// if err != nil {
// return Event{}, err
// }
//
// var evt Event
// err = sqlx.Bind(&evt, rows)
//
// return evt, err
}
func insert(db *sql.DB) iris.Handler {
return func(ctx iris.Context) {
var evt Event
if err := ctx.ReadJSON(&evt); err != nil {
errors.InvalidArgument.Details(ctx, "unable to read body", err.Error())
return
}
id, err := insertEvent(ctx, db, evt)
if err != nil {
errors.Internal.LogErr(ctx, err)
return
}
ctx.JSON(iris.Map{"id": id})
}
}
func list(db *sql.DB) iris.Handler {
return func(ctx iris.Context) {
events, err := listEvents(ctx, db)
if err != nil {
errors.Internal.LogErr(ctx, err)
return
}
ctx.JSON(events)
}
}
func getByID(db *sql.DB) iris.Handler {
return func(ctx iris.Context) {
eventID := ctx.Params().Get("event_id")
evt, err := getEvent(ctx, db, eventID)
if err != nil {
errors.Internal.LogErr(ctx, err)
return
}
ctx.JSON(evt)
}
}