File tree Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments