unrolled/render

Tucker Programming

[바미] Go - Render, Pat, Negroni

/main.go


package main

  type User struct {
    Name      string    `json:"name"`
    Email     string    `json:"email"`
    CreatedAt time.Time `json:"created_at"`
}

func getUserInfoHandler(w http.ResponseWriter, r *http.Request) {
    user := User{Name: "yklovejesus", Email: "[email protected]"}

  w.Header().Add("Content-type", "application/json")
  w.WriteHeader(http.StatusOK)
  data, _ := json.Marshal(user)
  fmt.Fprint(wm string(data))
}

func addUserHandler(w http.ResponseWriter, r *http.Request) {
    user := new(User)
    err := json.NewDecoder(r.Body).Decode(user)
    if err != nil {
        rd.Text(w, http.StatusBadRequest, err.Error())
        return
    }
    user.CreatedAt = time.Now()
  w.Header().Add("Content-type", "application/json")
  w.WriteHeader(http.StatusOK)
  data, _ := json.Marshal(user)
  fmt.Fprint(wm string(data)
}

func helloHandler(w http.ResponseWriter, r *http.Request) { // 2
  tmpl, err := template.new("Hello").ParseFiles("templates/hello.tmpl")
  if err != nil {
    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprint(w, err)
    return
  }
  tmpl.ExecuteTemplate(w, "hello.tmpl", "changbeom")
}

  func main() {
    mux := pat.New()

    mux.Get("/users", getUserInfoHandler) // 1
      mux.Post("/users", addUserHandler)
    mux.Get("/hello", helloHandler)

    http.ListenAndServe(":3000", mux)

gorilla/pat


  go get github.com/gorilla/pat

/templates/hello.html

<html>
  <head>
  <title>Hello Go in Web</title>
  </head>
  <body>
  Hello World{{.}}
  </body>
  </html>

이제 동작을 확인해보기 위해 클라이언트 앱으로 동작시켜보자!

GET

https://user-images.githubusercontent.com/33046341/93737442-2ea4eb80-fc1e-11ea-96f9-c659aae860d0.png

POST