|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +type Comment struct { |
| 12 | + Author string `json:"author"` |
| 13 | + Content string `json:"content"` |
| 14 | + Created time.Time `json:"created"` |
| 15 | +} |
| 16 | + |
| 17 | +type Comments []Comment |
| 18 | + |
| 19 | +const commentsFile = "comments.json" |
| 20 | + |
| 21 | +func loadComments() (Comments, error) { |
| 22 | + if _, err := os.Stat(commentsFile); os.IsNotExist(err) { |
| 23 | + return Comments{}, nil |
| 24 | + } |
| 25 | + |
| 26 | + data, err := os.ReadFile(commentsFile) |
| 27 | + if err != nil { |
| 28 | + return nil, err |
| 29 | + } |
| 30 | + |
| 31 | + var comments []Comment |
| 32 | + err = json.Unmarshal(data, &comments) |
| 33 | + if err != nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + |
| 37 | + return comments, nil |
| 38 | +} |
| 39 | + |
| 40 | +func writeComments(comments Comments) error { |
| 41 | + data, err := json.Marshal(comments) |
| 42 | + if err != nil { |
| 43 | + return err |
| 44 | + } |
| 45 | + |
| 46 | + err = os.WriteFile(commentsFile, data, 0644) |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + |
| 51 | + return nil |
| 52 | +} |
| 53 | + |
| 54 | +func handleComments(writer http.ResponseWriter, request *http.Request) { |
| 55 | + comments, err := loadComments() |
| 56 | + if err != nil { |
| 57 | + log.Print("loadComments:", err) |
| 58 | + writer.WriteHeader(http.StatusInternalServerError) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + switch request.Method { |
| 63 | + case http.MethodGet: |
| 64 | + writer.Header().Set("Content-Type", "application/json") |
| 65 | + |
| 66 | + err := json.NewEncoder(writer).Encode(comments) |
| 67 | + if err != nil { |
| 68 | + log.Print("json.NewEncoder.Encode:", err) |
| 69 | + writer.WriteHeader(http.StatusInternalServerError) |
| 70 | + } |
| 71 | + |
| 72 | + case http.MethodPost: |
| 73 | + var comment Comment |
| 74 | + err := json.NewDecoder(request.Body).Decode(&comment) |
| 75 | + if err != nil { |
| 76 | + log.Print("json.NewDecoder.Decode:", err) |
| 77 | + writer.WriteHeader(http.StatusBadRequest) |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + comments = append(comments, comment) |
| 82 | + |
| 83 | + err = writeComments(comments) |
| 84 | + if err != nil { |
| 85 | + log.Print("writeComments:", err) |
| 86 | + writer.WriteHeader(http.StatusInternalServerError) |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +func main() { |
| 92 | + http.HandleFunc("/comments", handleComments) |
| 93 | + |
| 94 | + log.Fatal(http.ListenAndServe(":8080", nil)) |
| 95 | +} |
0 commit comments