Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

Golang(Go) struct 에 대해서 알아보고 testcase 까지 작성

GOLANG, 20223 min read

struct 는 go 에서 class 와 가장 비슷하다

go 는 대소문자로 정보 은익?

go는 식별자의 첫 번째 문자가 대문자인지 소문자인지에 따라 public과 private 를 구분한다. 마찬가지로 구조체의 필드도 대문자로 시작하는 필드는 패키지 외부에서 접근할 수 있고 소문자로 시작하는 필드는 패키지 내부에서만 접근할 수 있다

omitempty

배경

type MemberInfo struct {
ID int64 json:"ID" `
Name string json:"title"`
Address string json:"address,omitempty"`
}

golang 을 사용하면 위 코드와 같이 struct 를 만들어서 요청의 body 의 json 값을 받거나 응답을 보내기전 dto 로 값을 채워 보낸다.

예를들어 회원의 등록된 주소(address)가 없다면 프론트에서 받은 응답 json 에 key 값이 안보이길 원한다.

omitempty 적용 비교 ,json 등등...

보통 프론트에서 받는 응답값을 보면

1.omitempty 표시 안했을 떄

{ID :1,name:"coco",address:""}

1.omitempty 표시 했을 떄

{ID :1,name:"coco"}

echo Struct Tag Binding

배경

2022/11/17 그런데 field 의 타입을 json 으로 쓴 경우 request body 를 bind 한다고 생각하기 때문에 body 값이 없어서 required tag 로 에러가 발생했다. Key: 'verification.Name' Error:Field validation for 'Name' failed on the 'required' tag

기존에 1.16 버전 사용시 ctx.Bind 를 했을 때 field 의 타입을 json 으로 써도 통과가 되었는데 더 엄격하게 변경된거 같다

Data Sources
Echo supports the following tags specifying data sources:
query - query parameter
param - path parameter (also called route)
header - header parameter
json - request body. Uses builtin Go json package for unmarshalling.
xml - request body. Uses builtin Go xml package for unmarshalling.
form - form data. Values are taken from query and request body. Uses Go standard library form parsing.

json 사용 경험

  1. 파일 업로드 기능이 필요
  2. 파일을 S3 에 저장하고 url을 받고 있음
  3. client 에서 service로 여러개의 파일을 보내야 하는 상황
{data:"https://test",data2:"https://test2"}
  1. client 에서 service로 json 데이터를 전송
{
files:{data:"https://test",data2:"https://test2"}
}
  • (echo contex 를 사용할 경우) 서비스 에서는 어떻게 json 형태를 인식할까?

go에서는 encoding/json 패키지를 사용해서 JSON 인코딩을 합니다.

  • Data struct filed 에 json.RawMessage 타입을 지정합니다.
type Data struct {
files json.RawMessage `query:"files'"`
}
  • echo.Context c.Bind(&Data) 를 사용하면 Data struct 에 bind 됩니다.

crypto test

참고

© 2024 by GwiyeomGo Tech Blog. All rights reserved.