-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.go
91 lines (78 loc) · 2.36 KB
/
crud.go
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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
// Item represents a simple item with ID and Name
type Item struct {
ID string `json:"id"`
Name string `json:"name"`
}
var items []Item
// CORS middleware
func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func createItem(w http.ResponseWriter, r *http.Request) {
var item Item
_ = json.NewDecoder(r.Body).Decode(&item)
items = append(items, item)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(item)
}
func getItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
func updateItem(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range items {
if item.ID == params["id"] {
items = append(items[:index], items[index+1:]...)
var updatedItem Item
_ = json.NewDecoder(r.Body).Decode(&updatedItem)
updatedItem.ID = params["id"]
items = append(items, updatedItem)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(updatedItem)
return
}
}
}
func deleteItem(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range items {
if item.ID == params["id"] {
items = append(items[:index], items[index+1:]...)
break
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
func main() {
router := mux.NewRouter()
// CRUD routes
router.HandleFunc("/items", createItem).Methods("POST")
router.HandleFunc("/items", getItems).Methods("GET")
router.HandleFunc("/items/{id}", updateItem).Methods("PUT")
router.HandleFunc("/items/{id}", deleteItem).Methods("DELETE")
// Root route
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to the Go CRUD API"))
}).Methods("GET")
// Apply CORS middleware
log.Fatal(http.ListenAndServe(":8000", enableCORS(router)))
}