|
| 1 | +package controllers |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + |
| 12 | + "github.com/gorilla/mux" |
| 13 | + "github.com/jackc/pgx/v4" |
| 14 | + |
| 15 | + "go_rest_api/models" |
| 16 | +) |
| 17 | + |
| 18 | +func GetProducts(db *pgx.Conn, w http.ResponseWriter, r *http.Request) { |
| 19 | + // Converting from string into int |
| 20 | + count, _ := strconv.Atoi(r.FormValue("count")) |
| 21 | + start, _ := strconv.Atoi(r.FormValue("start")) |
| 22 | + |
| 23 | + // If no count value given, set it as 10 by default |
| 24 | + if count <= 0 { |
| 25 | + count = 10 |
| 26 | + } |
| 27 | + fmt.Printf("%d", count) |
| 28 | + fmt.Printf("%d", start) |
| 29 | + // If no start value given, set it as 0 by default |
| 30 | + if start < 0 { |
| 31 | + start = 0 |
| 32 | + } |
| 33 | + |
| 34 | + products, err := models.GetProducts(db, start, count) |
| 35 | + if err != nil { |
| 36 | + // If error, return as internal server error |
| 37 | + respondWithError(w, http.StatusInternalServerError, err.Error()) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + respondWithJSON(w, http.StatusOK, products) |
| 42 | +} |
| 43 | + |
| 44 | +func GetProduct(db *pgx.Conn, w http.ResponseWriter, r *http.Request) { |
| 45 | + // Retrieve variables from the request payload |
| 46 | + vars := mux.Vars(r) |
| 47 | + |
| 48 | + // Converting from string into int |
| 49 | + id, err := strconv.Atoi(vars["id"]) |
| 50 | + if err != nil { |
| 51 | + // If error return with message |
| 52 | + respondWithError(w, http.StatusBadRequest, "Invalid product ID") |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + p := models.Product{ID: id} |
| 57 | + if err := p.GetProduct(db); err != nil { |
| 58 | + switch err { |
| 59 | + case sql.ErrNoRows: |
| 60 | + respondWithError(w, http.StatusNotFound, "Product not found") |
| 61 | + default: |
| 62 | + respondWithError(w, http.StatusInternalServerError, err.Error()) |
| 63 | + } |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + respondWithJSON(w, http.StatusOK, p) |
| 68 | +} |
| 69 | + |
| 70 | +func CreateProduct(db *pgx.Conn, w http.ResponseWriter, r *http.Request) { |
| 71 | + var p models.Product |
| 72 | + // Creating a log file to check |
| 73 | + file, err := os.OpenFile("gorilla-mux-restapi-postgres.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) |
| 74 | + // Read data from the request payload ( input stream ) |
| 75 | + decoder := json.NewDecoder(r.Body) |
| 76 | + |
| 77 | + // Set the output file for logging |
| 78 | + log.SetOutput(file) |
| 79 | + |
| 80 | + // Decoding the data and put into the product reference variable |
| 81 | + if err := decoder.Decode(&p); err != nil { |
| 82 | + // Logging if there is an err |
| 83 | + log.Fatal(err) |
| 84 | + respondWithError(w, http.StatusBadRequest, "Invalid payload") |
| 85 | + return |
| 86 | + } |
| 87 | + |
| 88 | + // Delaying the execution and closing it when the need is over |
| 89 | + defer r.Body.Close() |
| 90 | + |
| 91 | + if err != nil { |
| 92 | + log.Fatal(err) |
| 93 | + } |
| 94 | + |
| 95 | + if err := p.CreateProduct(db); err != nil { |
| 96 | + respondWithError(w, http.StatusInternalServerError, err.Error()) |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + respondWithJSON(w, http.StatusCreated, p) |
| 101 | +} |
| 102 | + |
| 103 | +// This function is used to update a product by giving the unique identifier (ID) |
| 104 | +func UpdateProduct(db *pgx.Conn, w http.ResponseWriter, r *http.Request) { |
| 105 | + // Retrieve variables from the request payload |
| 106 | + vars := mux.Vars(r) |
| 107 | + |
| 108 | + // Converting from string into int |
| 109 | + id, err := strconv.Atoi(vars["id"]) |
| 110 | + if err != nil { |
| 111 | + respondWithError(w, http.StatusBadRequest, "Invalid product ID") |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + var p models.Product |
| 116 | + |
| 117 | + // Read data from the request payload ( input stream ) |
| 118 | + decoder := json.NewDecoder(r.Body) |
| 119 | + |
| 120 | + // Decoding the data and put into the product reference variable |
| 121 | + if err := decoder.Decode(&p); err != nil { |
| 122 | + respondWithError(w, http.StatusBadRequest, "Invalid request payload") |
| 123 | + return |
| 124 | + } |
| 125 | + |
| 126 | + // Delaying the execution and closing it when the need is over |
| 127 | + defer r.Body.Close() |
| 128 | + p.ID = id |
| 129 | + |
| 130 | + if err := p.UpdateProduct(db); err != nil { |
| 131 | + respondWithError(w, http.StatusInternalServerError, err.Error()) |
| 132 | + return |
| 133 | + } |
| 134 | + |
| 135 | + respondWithJSON(w, http.StatusOK, p) |
| 136 | +} |
| 137 | + |
| 138 | +// This function is used to delete a product by giving the unique identifier (ID) |
| 139 | +func DeleteProduct(db *pgx.Conn, w http.ResponseWriter, r *http.Request) { |
| 140 | + vars := mux.Vars(r) |
| 141 | + id, err := strconv.Atoi(vars["id"]) |
| 142 | + if err != nil { |
| 143 | + respondWithError(w, http.StatusBadRequest, "Invalid Product ID") |
| 144 | + return |
| 145 | + } |
| 146 | + |
| 147 | + p := models.Product{ID: id} |
| 148 | + if err := p.DeleteProduct(db); err != nil { |
| 149 | + respondWithError(w, http.StatusInternalServerError, err.Error()) |
| 150 | + return |
| 151 | + } |
| 152 | + |
| 153 | + respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"}) |
| 154 | +} |
| 155 | + |
| 156 | +// This function is used to return the error with message in JSON format |
| 157 | +func respondWithError(w http.ResponseWriter, code int, message string) { |
| 158 | + // sending it as key-value pair using map |
| 159 | + respondWithJSON(w, code, map[string]string{"error": message}) |
| 160 | +} |
| 161 | + |
| 162 | +// This function is used to return the payload to the user in JSON format |
| 163 | +func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) { |
| 164 | + // Converting the payload to JSON |
| 165 | + response, _ := json.Marshal(payload) |
| 166 | + |
| 167 | + // Set the custom response header |
| 168 | + w.Header().Set("Content-Type", "application/json") |
| 169 | + w.WriteHeader(code) |
| 170 | + w.Write(response) |
| 171 | +} |
0 commit comments