typecode
GoHTTP Handler/handler.go
1package main
2
3import (
4 "encoding/json"
5 "net/http"
6 "sync"
7)
8
9type Item struct {
10 ID int `json:"id"`
11 Name string `json:"name"`
12 Price float64 `json:"price"`
13}
14
15type Store struct {
16 mu sync.RWMutex
17 items map[int]Item
18 nextID int
19}
20
21func NewStore() *Store {
22 return &Store{items: make(map[int]Item), nextID: 1}
23}
24
25func (s *Store) HandleList(w http.ResponseWriter, r *http.Request) {
26 s.mu.RLock()
27 defer s.mu.RUnlock()
28 result := make([]Item, 0, len(s.items))
29 for _, item := range s.items {
30 result = append(result, item)
31 }
32 w.Header().Set("Content-Type", "application/json")
33 json.NewEncoder(w).Encode(result)
34}
35
36func (s *Store) HandleCreate(w http.ResponseWriter, r *http.Request) {
37 var item Item
38 if err := json.NewDecoder(r.Body).Decode(&item); err != nil {
39 http.Error(w, err.Error(), http.StatusBadRequest)
40 return
41 }
42 s.mu.Lock()
43 item.ID = s.nextID
44 s.nextID++
45 s.items[item.ID] = item
46 s.mu.Unlock()
47 w.WriteHeader(http.StatusCreated)
48 json.NewEncoder(w).Encode(item)
49}
0WPM
100%Accuracy
00:00Time
0%
Progress