-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
108 lines (85 loc) · 2.02 KB
/
main.go
File metadata and controls
108 lines (85 loc) · 2.02 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync"
)
var cacheMutex sync.RWMutex
type User struct {
Name string `json: "Name, omitempty"`
Email string `json: "Email, omitempty"`
password string `json: "password, omitempty"`
displayName string `json: "displayName, omitempty"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("Post /users", createUser)
mux.HandleFunc("Get /users/{id}", getUser)
mux.HandleFunc("Delete /users/{id}", deleteUser)
fmt.Println("Server Listening to :8080")
http.ListenAndServe(":8080", mux)
}
func handleRoot(w http.ResponseWriter,
r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func deleteUser(w http.ResponseWriter,
r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, ok := userCache[id]
if !ok {
http.Error(w, "user not found", http.StatusBadRequest)
return
}
cacheMutex.Lock()
delete(userCache, id)
cacheMutex.Unlock()
w.WriteHeader(http.StatusNoContent)
}
func getUser(w http.ResponseWriter,
r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cacheMutex.RLock()
user, ok := userCache[id]
cacheMutex.RUnlock()
if !ok {
http.Error(w, "user not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
j, err := json.Marshal(user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(j)
}
func createUser(w http.ResponseWriter,
r *http.Request) {
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if user.Name == "" {
http.Error(w, "name is required", http.StatusBadRequest)
return
}
cacheMutex.Lock()
userCache[len(userCache)+1] = user
cacheMutex.Unlock()
w.WriteHeader(http.StatusNoContent)
}