backend (Go) 개발

http JSON

꼰대코더 2025. 3. 8. 00:51

struct 을 JSON string 으로 변환

type Book struct {
    Title string `json:"title"`
    Author string `json:"author"`
}

// an instance of our Book struct
book := Book{Title: "Learning Concurreny in Python", Author: "Elliot Forbes"}

byteArray, err := json.Marshal(book)
if err != nil {
    fmt.Println(err)
}

fmt.Println(string(byteArray))

 

struct 과 struct 속의 struct 을 JSON string 으로 변환

type Book struct {
    Title string `json:"title"`
    Author Author `json:"author"`
}

type Author struct {
    Sales int `json:"book_sales"`
    Age int `json:"age"`
    Developer bool `json:"is_developer"`
}

author := Author{Sales: 3, Age: 25, Developer: true}
book := Book{Title: "Learning Concurrency in Python", Author: author}

byteArray, err := json.Marshal(book) // //json.MarshalIndent(book, "", "  ")
if err != nil {
    fmt.Println(err)
}

fmt.Println(string(byteArray))

$ go run main.go
{"title":"Learning Concurrency in Python","author":{"book_sales":3,"age":25,"is_developer":true}}

 

JSON string 을 struct 으로 변환

type SensorReading struct {
    Name string `json:"name"`
    Capacity int `json:"capacity"`
    Time string `json:"time"`
}

jsonString := `{"name": "battery sensor", "capacity": 40, "time": "2019-01-21T19:07:28Z"}`

var reading SensorReading
err := json.Unmarshal([]byte(jsonString), &reading)
fmt.Printf("%+v\n", reading)

 

웹 api JSON
client

$ curl -X POST http://localhost:8080/decode \
   -d '
       {"name": "tomas",   "age": 31}
       {"name": "charles", "age": 48}
    '

 

Server

package main

import (
           "encoding/json"
           "errors"
           "fmt"
           "io"
           "log"
           "net/http"
           "os"
)

type Person struct {
           Name string `json: "name"`
           Age int `json: "age"`
}

func decodeHandler(w http.ResponseWriter, r *http.Request) {
           dec := json.NewDecoder(r.Body)
           var e *json.UnmarshalTypeError

           for {
                      var p Person
                      err := dec.Decode(&p)
                      if err == io.EOF {
                                 break
                      }
                      if errors.As(err, &e) {
                                 log.Println(err)
                                 continue
                      }
                      if err != nil {
                                 http.Error(w, err.Error(), http.StatusBadRequest)
                                 return
                      }

                      fmt.Println(p.Name, p.Age)
           }

           fmt.Fprintf(w, "OK")
}

func sayHello(w http.ResponseWriter, r *http.Request) {
           fmt.Fprintf(w, "Hi there!")
}

func setupHandler(mux *http.ServeMux) {
           mux.HandleFunc("/", sayHello)
           mux.HandleFunc("/person", decodeHandler)
}

func main() {
           listenAddr := os.Getenv("LISTEN_ADDR")
           if len(listenAddr) == 0 {
                      listenAddr = ":8080"
           }

           mux := http.NewServeMux()
           setupHandler(mux)
           log.Fatal(http.ListenAndServe(listenAddr, mux))
}

'backend (Go) 개발' 카테고리의 다른 글

http fileupload  (0) 2025.03.08
http parseQuery  (0) 2025.03.08
Build HTTP Server  (0) 2025.03.05
환경설정  (0) 2025.03.04