JSON Transfer

go 2022. 4. 14. 13:56

https://github.com/tuckersGo/goWeb/blob/master/web2/main.go

 

https://www.youtube.com/watch?v=vOW0j6hd-Rg&ab_channel=TuckerProgramming

 

package main

import (
  "encoding/json"
  "fmt"
  "net/http"
  "time"
)

type User struct {
  FirstName string
  LastName  string
  Email     string
  CreatedAt time.Time
}

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, "Bad Request: ", err)
    return
  }
  user.CreatedAt = time.Now()

  data, _ := json.Marshal(user)
  w.WriteHeader(http.StatusOK)
  fmt.Fprint(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)
}

 

URL에서 name값을 출력 

 

http://192.168.0.6:3000/bar?name='aaaaaa'

'go' 카테고리의 다른 글

go 프로젝트 세팅  (0) 2024.02.26
cryptopunks raritysniper json 파싱  (0) 2022.04.15
Web Handler  (0) 2022.04.14
go언어 설치  (0) 2022.04.14
routing module  (0) 2022.04.14
블로그 이미지

iesay

,