Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

Golang(Go) Unmarshal , Marshal

GOLANG, 20221 min read

배경

golang 코드를 짜면서 데이터의 형태를 변환하는 경우가 많다.. 요청값의 데이터를 바인드 할 때 혹은 내부 로직에서 데이터 타입을 바꿀 때 또는 응닶값의 데이터의 타입을 수정할때 등... 여러번 찾아서 코드를 수정한다. 한번쯤 정리하는것도 필요하다고 느낀다.

자주

내상황

  1. items 의 map 값을 string 으로 받았다.
var items []map[string]string
if err := builder.Find(&items); err != nil {
context.Log(c).Errorln(err.Error())
}
  1. 응답값은 []interface{} 형태이다.
id, _ := strconv.ParseInt(item["id"], 10, 64)
var confirmed map[string]interface{}
json.Unmarshal([]byte(item["confirmed"]), &confirmed)
result := map[string]interface{}{
"ID": id,
"confirmed": confirmed,
}
  1. 결국 응답값을 만들때 string 으로 넣어주고 있었다.

[]byte to json // JSON DECODING

  • func Unmarshal(data []byte, v interface{})

json to []byte // JSON ENCODING

*func Marshal(v interface{}) ([]byte, error)

실패 testcase 는 어떻게 만들까?

인터넷 예제를 찾아봤다 채널을 마샬링하면 에러가 발생한다고 한다

x := map[string]interface{}{
"foo": make(chan int),
}
_, err := json.Marshal(x)

참고

https://stackoverflow.com/questions/48898542/how-to-write-unit-test-for-failure-case-of-json-marshall https://ithub.tistory.com/333 https://freshman.tech/snippets/go/http-response-to-string/

© 2024 by GwiyeomGo Tech Blog. All rights reserved.