-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (71 loc) · 1.62 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
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"github.com/kelseyhightower/envconfig"
_ "github.com/lib/pq"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Config struct {
ConnString string `required:"true" split_words:"true"`
}
func main() {
var c Config
err := envconfig.Process("sapi", &c)
if err != nil {
log.Fatal(err.Error())
}
db, err := sql.Open("postgres", c.ConnString)
if err != nil {
log.Fatal(err)
}
defer db.Close()
http.HandleFunc("/products", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
rows, err := db.Query("SELECT id, name FROM products")
if err != nil {
http.Error(w, http.StatusText(500), 500)
log.Println(err)
return
}
defer rows.Close()
products := []Product{}
for rows.Next() {
var p Product
err := rows.Scan(&p.ID, &p.Name)
if err != nil {
http.Error(w, http.StatusText(500), 500)
log.Println(err)
return
}
products = append(products, p)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(products)
case "POST":
var p Product
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
http.Error(w, http.StatusText(400), 400)
log.Println(err)
return
}
_, err = db.Exec("INSERT INTO products (name) VALUES ($1)", p.Name)
if err != nil {
http.Error(w, http.StatusText(500), 500)
log.Println(err)
return
}
w.WriteHeader(http.StatusCreated)
default:
http.Error(w, http.StatusText(405), 405)
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}