-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
203 lines (163 loc) · 3.93 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
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
package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
type Book struct {
Id string `json:"id"`
Name string `json:"name"`
Author *Author `json:"author"`
PublishedOn time.Time `json:"publishedOn"`
}
type Author struct {
Name string `json:"name"`
Nationality string `json:"nationality"`
Age int `json:"age"`
}
func (book *Book) IsEmpty() bool {
if book.Name == "" || book.Author == nil {
return true
}
return false
}
var books = []Book{}
func main() {
fmt.Println("A simple in memory rest api")
router := mux.NewRouter()
// routes
router.HandleFunc("/", serveHome).Methods("GET")
router.HandleFunc("/books", getBooks).Methods("GET")
router.HandleFunc("/books", createBook).Methods("POST")
router.HandleFunc("/books/{id}", getBook).Methods("GET")
router.HandleFunc("/books/{id}", updateBook).Methods("PUT")
router.HandleFunc("/books/{id}", deleteBook).Methods("DELETE")
fmt.Println("Server is starting on port 5000...")
log.Fatal(http.ListenAndServe(":5000", router))
}
// Controllers
func serveHome(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
writer.Write([]byte(`
{
"message":"Server is ready to handle requests."
}
`))
}
func getBooks(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
json.NewEncoder(writer).Encode(books)
}
func getBook(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
params := mux.Vars(request)
for _, book := range books {
if book.Id == params["id"] {
json.NewEncoder(writer).Encode(book)
break
}
}
writer.Write([]byte(`
{
"message":"Book was not found"
}
`))
}
func createBook(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
if request.Body == nil {
writer.Write([]byte(`
{
"message":"Send book details in body"
}
`))
return
}
var book Book
json.NewDecoder(request.Body).Decode(&book)
if book.IsEmpty() {
writer.Write([]byte(`
{
"message":"Name and author are required fields"
}
`))
return
}
bookId, err := generateRandomId()
if err != nil {
writer.Write([]byte(`
{
"message":"Failed to generate book id"
}
`))
return
}
book.Id = bookId
book.PublishedOn = time.Now()
books = append(books, book)
json.NewEncoder(writer).Encode(book)
}
func updateBook(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
params := mux.Vars(request)
if request.Body == nil {
writer.Write([]byte(`
{
"message":"Provide fields to update"
}
`))
return
}
for index, book := range books {
if book.Id == params["id"] {
books = append(books[:index], books[index+1:]...) // Removing the book that is being edited
var book Book
json.NewDecoder(request.Body).Decode(&book)
book.Id = params["id"]
books = append(books, book) // appending the edited book
json.NewEncoder(writer).Encode(book)
return
}
}
writer.Write([]byte(`
{
"message":"Book not found"
}
`))
}
func deleteBook(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("content-type", "application/json")
params := mux.Vars(request)
for index, book := range books {
if book.Id == params["id"] {
books = append(books[:index], books[index+1:]...)
writer.Write([]byte(`
{
"message":"Book deleted"
}
`))
return
}
}
writer.Write([]byte(`
{
"message":"Book not found"
}
`))
}
func generateRandomId() (string, error) {
timestamp := time.Now().UnixNano()
randomBytes := make([]byte, 4)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
randomHex := hex.EncodeToString(randomBytes)
uniqueID := fmt.Sprintf("%d%s", timestamp, randomHex)
return uniqueID, nil
}