summaryrefslogtreecommitdiff
path: root/backend/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'backend/main.go')
-rw-r--r--backend/main.go67
1 files changed, 65 insertions, 2 deletions
diff --git a/backend/main.go b/backend/main.go
index 7376bd0..c39f123 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -1,6 +1,8 @@
package main
import "fmt"
+import "io"
+import "io/ioutil"
import "net/http"
import "os"
import "strconv"
@@ -56,7 +58,70 @@ func RecipeList(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(resp); err != nil {
panic(err)
}
+ } else if r.Method == "POST" {
+ var recipe *Recipe
+
+ body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
+ if err != nil {
+ panic(err)
+ }
+
+ err = r.Body.Close()
+ if err != nil {
+ panic(err)
+ }
+
+ err = json.Unmarshal(body, &recipe)
+ if err != nil {
+ w.WriteHeader(http.StatusUnprocessableEntity)
+ w.Header().Set("Content-Type", "application/json; charset=UTF-8")
+ resp := APIResponseItem{
+ Status: APIError{
+ Code: http.StatusUnprocessableEntity,
+ Msg: "Invalid Recipe"},
+ Data: make([]APIDataRecipe, 0),
+ }
+ if err := json.NewEncoder(w).Encode(resp); err != nil {
+ panic(err)
+ }
+ return
+ }
+
+ err = AddRecipeDB(recipe, db)
+ if err != nil {
+ resp := APIResponseItem{
+ Status: APIError{Code: http.StatusBadRequest,
+ Msg: "Recipe could not be added"},
+ Data: make([]APIDataRecipe, 0),
+ }
+
+ resp.Data = append(resp.Data, APIDataRecipe{recipe})
+
+ w.Header().Set("Content-Type",
+ "application/json; charset=UTF-8")
+ w.WriteHeader(http.StatusBadRequest)
+ if err := json.NewEncoder(w).Encode(resp); err != nil {
+ panic(err)
+ }
+ return
+ }
+
+ resp := APIResponseItem{
+ Status: APIError{Code: http.StatusCreated,
+ Msg: "Recipe added successfully"},
+ Data: make([]APIDataRecipe, 0),
+ }
+
+ resp.Data = append(resp.Data, APIDataRecipe{recipe})
+
+ w.Header().Set("Content-Type", "application/json; charset=UTF-8")
+ w.WriteHeader(http.StatusCreated)
+ if err := json.NewEncoder(w).Encode(resp); err != nil {
+ panic(err)
+ }
+
}
+
}
func SingleRecipe(w http.ResponseWriter, r *http.Request) {
@@ -77,7 +142,6 @@ func SingleRecipe(w http.ResponseWriter, r *http.Request) {
status = http.StatusOK
msg = "Successful"
}
- fmt.Println(status, msg, recipe)
resp := APIResponseItem{
Status: APIError{Code: status, Msg: msg},
@@ -119,7 +183,6 @@ func main() {
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")