diff options
author | Tucker Evans <tuckerevans24@gmail.com> | 2019-11-10 14:32:40 -0500 |
---|---|---|
committer | Tucker Evans <tuckerevans24@gmail.com> | 2019-11-10 14:32:40 -0500 |
commit | 898a9ed40e4422d9062b58efaf070cf31a7ef168 (patch) | |
tree | 17eb5cd9578f08f5afba3af3e26f272ef995d85c /backend/main.go | |
parent | 25e9d6a91903b45d6a62a152e230bfdbc6a41af0 (diff) |
Add create recipe functionality
Diffstat (limited to 'backend/main.go')
-rw-r--r-- | backend/main.go | 67 |
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") |