-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
88 lines (74 loc) · 2.21 KB
/
main.go
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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/google/uuid"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"http-server/users"
)
var serverName string
func main() {
logfile, err := os.OpenFile("server.log", os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
fmt.Printf("error opening file: %v", err)
}
defer logfile.Close()
initLog(logfile)
r := mux.NewRouter()
r.HandleFunc("/", testHandler).Methods("GET")
r.HandleFunc("/users", listUsers).Methods("GET")
r.HandleFunc("/user", addUser).Methods("POST")
r.HandleFunc("/user/{id}", deleteUser).Methods("DELETE")
serverName = os.Getenv("SERVER_NAME")
if serverName == "" {
serverName = "Default server"
}
log.Debugln("Starting Server on Port 8081 on", serverName)
fmt.Println("Starting Server on Port 8081 on", serverName)
log.Fatal(http.ListenAndServe(":8081", r))
}
func testHandler(w http.ResponseWriter, r *http.Request) {
log.Debugln("Request hit to fetch users list")
log.Debugln("Users :", users.Users)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode("Server is Working")
}
func listUsers(w http.ResponseWriter, r *http.Request) {
log.Debugln("Request hit to fetch users list")
log.Debugln("Users :", users.Users)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users.Users)
}
func addUser(w http.ResponseWriter, r *http.Request) {
log.Debugln("Request hit to create a user")
w.Header().Set("Content-Type", "application/json")
var u users.User
json.NewDecoder(r.Body).Decode(&u)
u.Id = uuid.NewString()
users.Users = append(users.Users, u)
log.Debugln("User :", u)
json.NewEncoder(w).Encode(users.Users)
}
func deleteUser(w http.ResponseWriter, r *http.Request) {
log.Debugln("Request hit to delete a user")
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
id := params["id"]
for i, u := range users.Users {
if u.Id == id {
log.Debugln("User :", u)
users.Users = append(users.Users[:i], users.Users[i+1:]...)
break
}
}
json.NewEncoder(w).Encode("User deleted successfully")
}
func initLog(f *os.File) {
log.SetOutput(f)
log.SetLevel(log.DebugLevel)
log.SetReportCaller(true)
log.SetFormatter(&log.JSONFormatter{})
}