-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
265 lines (232 loc) · 6.34 KB
/
server.go
File metadata and controls
265 lines (232 loc) · 6.34 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// @title Demo API
// @description A simple demo API in Go with streaming support
// @host localhost:5000
// @version 1.0
// @BasePath /v1.0
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"time"
httpSwagger "github.com/swaggo/http-swagger"
_ "demo-api/docs" // register OpenAPI spec inside swaggo
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
type APIResponse struct {
Status string `json:"status"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
var (
users = map[int]User{}
usersMutex sync.Mutex
nextID = 1
)
func main() {
// Serve REST endpoints.
http.HandleFunc("/v1.0/status", statusHandler)
http.HandleFunc("/v1.0/users", usersHandler)
http.HandleFunc("/v1.0/stream/time", timeStreamHandler)
// Serve Swagger UI.
http.Handle("/swagger/", httpSwagger.Handler(
httpSwagger.URL("http://localhost:5000/swagger/doc.json"),
))
// Serve static files from ./static.
http.Handle("/v1.0/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
fmt.Println("HTTP server listening on port 5000")
fmt.Println("Swagger UI: http://localhost:5000/swagger/index.html")
fmt.Println("time.html: http://localhost:5000/static/time.html")
fmt.Println("SSE endpoint: http://localhost:5000/stream/time")
log.Fatal(http.ListenAndServe(":5000", nil))
}
// @Summary Return status
// @Description Returns version, uptime, and the number of connections
// @Tags status
// @Produce json
// @Success 200 {object} APIResponse
// @Router /status [get]
func statusHandler(w http.ResponseWriter, r *http.Request) {
response := map[string]interface{}{
"version": "0.1.2",
"uptime": "1h2m3s",
"connections": 3,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
// @Summary Users API
// @Description Handles GET, POST, PATCH, DELETE for users
// @Tags users
// @Produce json
// @Param id query int false "User ID for GET, PATCH, DELETE"
// @Param user body User false "User object for POST/PATCH"
// @Success 200 {object} APIResponse
// @Failure 400 {object} APIResponse
// @Router /users [get]
// @Router /users [post]
// @Router /users [patch]
// @Router /users [delete]
func usersHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
usersGetHandler(w, r)
case http.MethodPost:
usersPostHandler(w, r)
case http.MethodPatch:
usersPatchHandler(w, r)
case http.MethodDelete:
usersDeleteHandler(w, r)
default:
http.Error(w, "method not supported", http.StatusMethodNotAllowed)
}
}
// GET /users
func usersGetHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
usersMutex.Lock()
defer usersMutex.Unlock()
if idStr == "" {
list := make([]User, 0, len(users))
for _, u := range users {
list = append(list, u)
}
writeJSON(w, APIResponse{Status: "ok", Data: list})
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
writeJSON(w, APIResponse{Status: "error", Error: "invalid id"})
return
}
user, ok := users[id]
if !ok {
writeJSON(w, APIResponse{Status: "error", Error: "user not found"})
return
}
writeJSON(w, APIResponse{Status: "ok", Data: user})
}
// POST /users
func usersPostHandler(w http.ResponseWriter, r *http.Request) {
var newUser User
if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
writeJSON(w, APIResponse{
Status: "error",
Error: "invalid JSON",
})
return
}
usersMutex.Lock()
defer usersMutex.Unlock()
for _, u := range users {
if u.Name == newUser.Name {
writeJSON(w, APIResponse{
Status: "error",
Error: fmt.Sprintf("user with name '%s' already exists", newUser.Name),
})
return
}
}
newUser.ID = nextID
nextID++
users[newUser.ID] = newUser
writeJSON(w, APIResponse{
Status: "ok",
Data: newUser,
})
}
// PATCH /users
func usersPatchHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
writeJSON(w, APIResponse{Status: "error", Error: "missing id"})
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
writeJSON(w, APIResponse{Status: "error", Error: "invalid id"})
return
}
var update User
if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
writeJSON(w, APIResponse{Status: "error", Error: "invalid JSON"})
return
}
usersMutex.Lock()
defer usersMutex.Unlock()
user, ok := users[id]
if !ok {
writeJSON(w, APIResponse{Status: "error", Error: "user not found"})
return
}
if update.Name != "" {
user.Name = update.Name
}
users[id] = user
writeJSON(w, APIResponse{Status: "ok", Data: user})
}
// DELETE /users
func usersDeleteHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
id, err := strconv.Atoi(idStr)
if err != nil {
writeJSON(w, APIResponse{Status: "error", Error: "invalid id"})
return
}
usersMutex.Lock()
defer usersMutex.Unlock()
if _, ok := users[id]; !ok {
writeJSON(w, APIResponse{Status: "error", Error: "user not found"})
return
}
delete(users, id)
writeJSON(w, APIResponse{Status: "ok", Data: map[string]int{"deleted": id}})
}
// @Summary Stream server time every second
// @Description Returns server time every second until the client disconnects
// @Tags stream
// @Produce text/event-stream
// @Success 200 {string} string "Server-sent events stream"
// @Router /stream/time [get]
func timeStreamHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported!", http.StatusInternalServerError)
return
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
eventID := 0
for {
select {
case <-r.Context().Done():
fmt.Println("client closed connection")
return
case t := <-ticker.C:
// SSE messages must follow this format:
// field-name: field-value
// field-name: field-value
// ...
// <blank line marks end>
eventID++
fmt.Fprintf(w, "id: %03d\n", eventID)
fmt.Fprintf(w, "data: %s\n", t.Format(time.RFC3339))
fmt.Fprintf(w, "\n")
flusher.Flush()
}
}
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}