|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "math/rand" |
| 8 | + "net/http" |
| 9 | + "strconv" |
| 10 | + "sync" |
| 11 | +) |
| 12 | + |
| 13 | +type Book struct { |
| 14 | + ID int `json:"id"` |
| 15 | + Title string `json:"title"` |
| 16 | + Author string `json:"author"` |
| 17 | +} |
| 18 | + |
| 19 | +var ( |
| 20 | + books = make([]Book, 0) |
| 21 | + mu sync.Mutex |
| 22 | +) |
| 23 | + |
| 24 | +func main() { |
| 25 | + http.HandleFunc("/books", booksHandler) |
| 26 | + http.HandleFunc("/books/", bookByIDHandler) |
| 27 | + fmt.Println("Server running at http://localhost:8080") |
| 28 | + log.Fatal(http.ListenAndServe(":8080", nil)) |
| 29 | +} |
| 30 | + |
| 31 | +func booksHandler(w http.ResponseWriter, r *http.Request) { |
| 32 | + switch r.Method { |
| 33 | + case http.MethodGet: |
| 34 | + mu.Lock() |
| 35 | + defer mu.Unlock() |
| 36 | + json.NewEncoder(w).Encode(books) |
| 37 | + |
| 38 | + case http.MethodPost: |
| 39 | + var b Book |
| 40 | + if err := json.NewDecoder(r.Body).Decode(&b); err != nil { |
| 41 | + http.Error(w, "Invalid JSON", http.StatusBadRequest) |
| 42 | + return |
| 43 | + } |
| 44 | + mu.Lock() |
| 45 | + b.ID = rand.Intn(1000000) |
| 46 | + books = append(books, b) |
| 47 | + mu.Unlock() |
| 48 | + w.WriteHeader(http.StatusCreated) |
| 49 | + json.NewEncoder(w).Encode(b) |
| 50 | + |
| 51 | + default: |
| 52 | + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +func bookByIDHandler(w http.ResponseWriter, r *http.Request) { |
| 57 | + idStr := r.URL.Path[len("/books/"):] |
| 58 | + id, err := strconv.Atoi(idStr) |
| 59 | + if err != nil { |
| 60 | + http.Error(w, "Invalid ID", http.StatusBadRequest) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + mu.Lock() |
| 65 | + defer mu.Unlock() |
| 66 | + |
| 67 | + for i, b := range books { |
| 68 | + if b.ID == id { |
| 69 | + if r.Method == http.MethodDelete { |
| 70 | + books = append(books[:i], books[i+1:]...) |
| 71 | + w.WriteHeader(http.StatusNoContent) |
| 72 | + return |
| 73 | + } |
| 74 | + json.NewEncoder(w).Encode(b) |
| 75 | + return |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + http.NotFound(w, r) |
| 80 | +} |
0 commit comments