[Go] json

psh_ros·2023년 1월 18일
0

Golang

목록 보기
1/2

내장 라이브러리인 encoding/json 패키지를 사용

go언어 에서 json을 다루는 다양한 방법을 알아본다.

Marshal

-> 데이터 구조 ==> byte 배열

사용방법 ----

type Message struct{
   Sender string
   Content string
}

func main() {
   http.HandlerFunc("/json", JsonHandler)
   log.Printf("Server started at localhost:%v","8080")
   log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", 8080, nil))
}

func JsonHandler(w http.ResponseWriter, r *http.Request) {
	message := Message{Sender:"rose", Content:"내용"}
   jsonMessage, _ := json.Marshal(message)
   fmt.Fprint(w, string(data))
}

구조체 태그 사용 ----

type Message struct{
   Sender string	`json:"sender"` 	// 필드 key값 변경
   Content string	`json:"_"`			// 필드를 출력하지 않기
   Receiver string `json:", omitempty"`	// 값이 비어있다면 필드를 출력하지 않기
   Size int `json:"data, string"		// 필드명을 data로 바꾸고 출력을 문자열로 변환
}

양식 지정 ----

func JsonHandler(w http.ResponseWriter, r *http.Request) {
	message := Message{Sender:"rose", Content:"내용"}
   jsonMessage, _ := json.MarshalIndent(message, "", " ")
   fmt.Println(string(jsonMessage)
}

채널 , 복소수(complex), 순환 참조는 JSON으로 인코딩 할 수 없다

NewEncoder

-> http의 writer를 매개변수로 json을 응답하는 인코더를 반환

사용방법 ----

func JsonHandler(w http.ResponseWriter, r *http.Request) {
	message := Message{Sender:"rose", Content:"내용"}
    jsonEncoder := json.NewEncoder(w)
    jsonEncoder.Encode(&message)
}

기존의 marshal 함수를 이용하고 응답 스트립에 바이트 배열을 쓰는것 보다 50% 가량 빠르게 작동한다.

Unmarshal

-> byte 배열 ==> 데이터 구조

사용방법 ----

type MessageRequest struct {
	Name string `json:"name"`	// 이런식으로 요청 양식을 지정해주면 속도를 더 높일 수 있다.
}

func JsonHandler(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	var request MessageRequest
	_ = json.Unmarshal(body, &request) // request에 body의 json값이 들어감
    
	response := request.Name + "에게서 요청이 왔습니다."
	encoder := json.NewEncoder(w)
	encoder.Encode(response)
}
  • 테스트 방법(터미널) : curl localhost:8080/json -d '{"name":"rose"}'

NewDecoder

-> request에서 json을 읽는 새 디코더를 반환

사용방법 ----

func JsonHandler(w http.ResponseWriter, r *http.Request) {
	var request MessageRequest
    decoder := json.NewDecoder(r.body)
    _ := decoder.Decode(&request)	// decoder의 버퍼의 값이 request에 할당됨
    
    response := request.Name + "에게서 요청이 왔습니다."
	encoder := json.NewEncoder(w)
	encoder.Encode(response)
}
  • 테스트 방법(터미널) : curl localhost:8080/json -d '{"name":"rose"}'

이것 또한 Unmarshal함수를 사용하는 것 보다 더 빠르게 작동한다.

Refereces: Building Microservices with Go (by Nic Jackson (Author))

0개의 댓글