krovn

Untitled

Oct 24th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.24 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     "net/http"
  7.  
  8.     "github.com/jkrovnl/rkods/models"
  9.     "github.com/julienschmidt/httprouter"
  10. )
  11.  
  12. func main() {
  13.     r := httprouter.New()
  14.     r.GET("/", index)
  15.     //added route plus parameter
  16.     r.GET("/user/:id", getUser)
  17.     http.ListenAndServe("localhost:8080", r)
  18. }
  19.  
  20. func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  21.     s := `<!DOCTYPE html>
  22.     <html lang="en">
  23.     <head>
  24.     <meta charset="UTF-8">
  25.     <title>Index</title>
  26.     </head>
  27.     <body>
  28.     <a href="/user/9872309847">GO TO: http://localhost:8080/user/9872309847</a>
  29.     </body>
  30.     </html>`
  31.     w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  32.     w.WriteHeader(http.StatusOK)
  33.     w.Write([]byte(s))
  34. }
  35.  
  36. func getUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
  37.     u := models.User{
  38.         Name:   "James Bond",
  39.         Gender: "male",
  40.         Age:    32,
  41.         Id:     p.ByName("id"),
  42.     }
  43.     //Marshal into JSON
  44.     uj, err := json.Marshal(u)
  45.     if err != nil {
  46.         fmt.Println(err)
  47.     }
  48.     //Write content-type, statuscode, payload
  49.     w.Header().Set("Content-Type", "application/json")
  50.     w.WriteHeader(http.StatusOK) //200
  51.     fmt.Fprintf(w, "%s\n", uj)
  52. }
  53. //
  54. //  Start your server
  55. //  Enter this at the terminal
  56. //  curl http://localhost:8080/user/1
  57. //
Advertisement
Add Comment
Please, Sign In to add comment