-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
143 lines (116 loc) · 3.79 KB
/
service.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
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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"usersapi_go/model"
"usersapi_go/connection"
"gopkg.in/mgo.v2/bson"
)
/*=============================================
= Home Method =
=============================================*/
func methodHome(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode("API Users UP!")
}
/*=============================================
= Create User Function =
=============================================*/
func createUser(w http.ResponseWriter, r*http.Request) {
defer r.Body.Close()
var user model.User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
fmt.Println(err)
SendError(w, http.StatusBadRequest, "Invalid request")
return
}
user.ID = bson.NewObjectId()
if err := connection.Insert(user); err != nil {
SendError(w, http.StatusInternalServerError, err.Error())
return
}
Response(w, http.StatusCreated, user)
}
/*=============================================
= Find User By Id =
=============================================*/
func findUserByID(w http.ResponseWriter, r*http.Request){
params := mux.Vars(r)
userID, err := strconv.Atoi(params["userId"])
if err != nil {
SendError(w, http.StatusBadRequest, "Invalid ID for User")
return
}
user, err := connection.FindByUser(userID)
if err != nil {
SendError(w, http.StatusBadRequest, "Error trying get data for user")
return
}
Response(w, http.StatusOK, user)
}
/*=============================================
= Find And Update =
=============================================*/
func updateUser(w http.ResponseWriter, r*http.Request) {
defer r.Body.Close()
var user model.User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
SendError(w, http.StatusBadRequest, "Invalid request")
return
}
if err := connection.Update(user); err != nil {
SendError(w, http.StatusInternalServerError, err.Error())
return
}
Response(w, http.StatusOK, map[string]string{"Response": "success"})
}
/*=============================================
= Delete User By ID =
=============================================*/
func deleteUser(w http.ResponseWriter, r*http.Request) {
defer r.Body.Close()
var user model.User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
SendError(w, http.StatusBadRequest, "Invalid request")
return
}
if err := connection.Delete(user); err != nil {
SendError(w, http.StatusInternalServerError, err.Error())
return
}
Response(w, http.StatusOK, map[string]string{"Response": "success"})
}
// SendError -- Send error function
func SendError(w http.ResponseWriter, code int, message string) {
Response(w, code, map[string]string{"Error!!": message})
}
// Response -- response function
func Response(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
// -----------------------------
/*=============================================
= Main Func App =
=============================================*/
func main() {
// ? port application
port := ":8236"
// ? router definition
r := mux.NewRouter()
// ? handle router
r.HandleFunc("/", methodHome).Methods("GET")
r.HandleFunc("/create/user", createUser).Methods("POST")
r.HandleFunc("/update/user/{userId}", updateUser).Methods("PUT")
r.HandleFunc("/delete/user/", deleteUser).Methods("DELETE")
r.HandleFunc("/user/{userId}", findUserByID).Methods("GET")
// ? server
fmt.Println(fmt.Sprintf("Server running on http://localhost%s", port))
log.Fatal(http.ListenAndServe(port, r))
}