package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
type User struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}
type fooHandler struct{}
func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
user := new(User)
err := json.NewDecoder(r.Body).Decode(user)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err)
return
}
user.CreatedAt = time.Now()
data, _ := json.Marshal(user)
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, string(data))
}
func barHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
fmt.Fprintf(w, "Hello %s!", name)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello world")
})
mux.HandleFunc("/bar", barHandler)
mux.Handle("/foo", &fooHandler{})
http.ListenAndServe(":3000", mux)
}
json.NewDecoder(r.Body).Decode(user) :: r.Body를 읽어서 user형태로 디코딩 처리
json.Marshal(user) :: user타입 데이터를 byte[]와 error로 변환
string(data) :: byte[]로 변환된 데이터를 String타입으로 형변환
참고 :: https://www.youtube.com/watch?v=vOW0j6hd-Rg&list=PLy-g2fnSzUTDALoERcKDniql16SAaQYHF&index=2