Created
June 28, 2023 12:10
-
-
Save zinevych/0702ac95cc277ecf8558482130eecf39 to your computer and use it in GitHub Desktop.
CRUD generated as output of Copilot X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type User struct { | |
ID int `json:"id"` | |
Name string `json:"name"` | |
Email string `json:"email"` | |
} | |
var users []User | |
func main() { | |
http.HandleFunc("/users", getUsers) | |
http.HandleFunc("/users/create", createUser) | |
http.HandleFunc("/users/update", updateUser) | |
http.HandleFunc("/users/delete", deleteUser) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
func getUsers(w http.ResponseWriter, r *http.Request) { | |
json.NewEncoder(w).Encode(users) | |
} | |
func createUser(w http.ResponseWriter, r *http.Request) { | |
var user User | |
err := json.NewDecoder(r.Body).Decode(&user) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
users = append(users, user) | |
json.NewEncoder(w).Encode(user) | |
} | |
func updateUser(w http.ResponseWriter, r *http.Request) { | |
var user User | |
err := json.NewDecoder(r.Body).Decode(&user) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
for i, u := range users { | |
if u.ID == user.ID { | |
users[i] = user | |
json.NewEncoder(w).Encode(user) | |
return | |
} | |
} | |
http.Error(w, "User not found", http.StatusNotFound) | |
} | |
func deleteUser(w http.ResponseWriter, r *http.Request) { | |
var user User | |
err := json.NewDecoder(r.Body).Decode(&user) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
for i, u := range users { | |
if u.ID == user.ID { | |
users = append(users[:i], users[i+1:]...) | |
json.NewEncoder(w).Encode(user) | |
return | |
} | |
} | |
http.Error(w, "User not found", http.StatusNotFound) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment