Skip to content

Commit 32da9c2

Browse files
committed
REST API | Get User
1 parent 036ac1d commit 32da9c2

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

118-MongoDB-REST/02-json/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Using Curl
2+
3+
1. Start your server
4+
5+
1. Enter this at the terminal
6+
```
7+
curl http://localhost:8080/user/1
8+
```

118-MongoDB-REST/02-json/main.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"log"
7+
8+
"net/http"
9+
10+
"github.com/aditya43/golang-core/118-mongodb-rest/02-json/models"
11+
"github.com/julienschmidt/httprouter"
12+
)
13+
14+
func main() {
15+
r := httprouter.New()
16+
r.GET("/", index)
17+
// added route plus parameter
18+
r.GET("/user/:id", getUser)
19+
log.Fatalln(http.ListenAndServe("localhost:8080", r))
20+
}
21+
22+
func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
23+
s := `<!DOCTYPE html>
24+
<html lang="en">
25+
<head>
26+
<meta charset="UTF-8">
27+
<title>Index</title>
28+
</head>
29+
<body>
30+
<a href="/user/9872309847">GO TO: http://localhost:8080/user/9872309847</a>
31+
</body>
32+
</html>
33+
`
34+
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
35+
w.WriteHeader(http.StatusOK)
36+
_, _ = w.Write([]byte(s))
37+
}
38+
39+
// changed func name
40+
func getUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
41+
u := models.User{
42+
Name: "James Bond",
43+
Gender: "male",
44+
Age: 32,
45+
Id: p.ByName("id"),
46+
}
47+
48+
// Marshal into JSON
49+
uj, err := json.Marshal(u)
50+
if err != nil {
51+
fmt.Println(err)
52+
}
53+
54+
// Write content-type, statuscode, payload
55+
w.Header().Set("Content-Type", "application/json")
56+
w.WriteHeader(http.StatusOK) // 200
57+
fmt.Fprintf(w, "%s\n", uj)
58+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package models
2+
3+
type User struct {
4+
Name string `json:"name"`
5+
Gender string `json:"gender"`
6+
Age int `json:"age"`
7+
Id string `json:"id"`
8+
}

0 commit comments

Comments
 (0)