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
|
package main
import "fmt"
import "net/http"
import "os"
import "strconv"
import _ "github.com/lib/pq"
import "database/sql"
import "encoding/json"
type APIError struct {
Code int
Msg string
}
type APIDataIds struct {
Ids interface{}
}
type APIDataRecipe struct {
Recipe interface{}
}
type APIResponseList struct {
Status APIError
Data []APIDataIds
}
type APIResponseItem struct {
Status APIError
Data []APIDataRecipe
}
func RecipeList(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
var ids []int
var id int
rows, err := db.Query("SELECT id FROM recipes")
if err != nil {
} else {
for rows.Next() {
rows.Scan(&id)
ids = append(ids, id)
}
}
resp := APIResponseList{
Status: APIError{Code: 200, Msg: "Successful Request"},
Data: make([]APIDataIds, 0),
}
resp.Data = append(resp.Data, APIDataIds{Ids: ids})
output, err := json.MarshalIndent(resp, "", " ")
if err != nil {
fmt.Println("Error converting to JSON")
} else {
fmt.Println(string(output))
}
}
}
func SingleRecipe(w http.ResponseWriter, r *http.Request) {
recipe_id, err := strconv.Atoi(r.URL.Path[len("/recipes/"):])
if err != nil {
fmt.Println("Not a valid ID")
return
}
if r.Method == "GET" {
recipe := RecipeFromId(recipe_id, db)
if recipe == nil {
recipe = MakeRecipe()
}
resp := APIResponseItem{
Status: APIError{Code: 200, Msg: "Successful Request"},
Data: make([]APIDataRecipe, 0),
}
resp.Data = append(resp.Data, APIDataRecipe{recipe})
output, err := json.MarshalIndent(resp, "", " ")
if err != nil {
fmt.Println("Error converting to JSON")
} else {
fmt.Println(string(output))
}
} else if r.Method == "POST" {
fmt.Printf("Create recipe \"%d\"...\n", recipe_id)
} else if r.Method == "PUT" {
fmt.Printf("Update recipe \"%d\"...\n", recipe_id)
} else if r.Method == "DELETE" {
fmt.Printf("Delete recipe \"%d\"...\n", recipe_id)
}
}
var DB_PASSWORD string
var DB_USER string
var db *sql.DB
const DB_NAME = "recipe_buddy"
func init() {
DB_PASSWORD = os.Getenv("DATABASE_PASSWORD")
DB_USER = os.Getenv("DATABASE_USER")
}
func main() {
var err error
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
DB_USER, DB_PASSWORD, DB_NAME)
fmt.Println(dbinfo)
db, err = sql.Open("postgres", dbinfo)
if err != nil || db.Ping() != nil {
fmt.Println("Error connecting to database")
}
http.HandleFunc("/recipes", RecipeList)
http.HandleFunc("/recipes/", SingleRecipe)
http.ListenAndServe(":8888", nil)
}
|