Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "github.com/jkrovnl/rkods/models"
- "github.com/julienschmidt/httprouter"
- )
- func main() {
- r := httprouter.New()
- r.GET("/", index)
- //added route plus parameter
- r.GET("/user/:id", getUser)
- http.ListenAndServe("localhost:8080", r)
- }
- func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- s := `<!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Index</title>
- </head>
- <body>
- <a href="/user/9872309847">GO TO: http://localhost:8080/user/9872309847</a>
- </body>
- </html>`
- w.Header().Set("Content-Type", "text/html; charset=UTF-8")
- w.WriteHeader(http.StatusOK)
- w.Write([]byte(s))
- }
- func getUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
- u := models.User{
- Name: "James Bond",
- Gender: "male",
- Age: 32,
- Id: p.ByName("id"),
- }
- //Marshal into JSON
- uj, err := json.Marshal(u)
- if err != nil {
- fmt.Println(err)
- }
- //Write content-type, statuscode, payload
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK) //200
- fmt.Fprintf(w, "%s\n", uj)
- }
- //
- // Start your server
- // Enter this at the terminal
- // curl http://localhost:8080/user/1
- //
Advertisement
Add Comment
Please, Sign In to add comment