개발/golang
-
[ Golang ] Rest Api 스펙이 틀릴때 (타입이 틀릴때) Json decode(Unmarshal) 하기개발/golang 2021. 4. 2. 21:08
외부 혹은 내부 Rest API 를 사용할때 문서에 적혀있는 스펙과 다른 타입을 반환할때가 종종있다. 이럴때 그냥 그대로 json decode (unmarshal) 를 하게될경우 err 가 발생하는것을 확인할수 있다. 따라서 아래와 같이 예방할수있다. package example_wrong_type_api_spec import ( "encoding/json" "strconv" "strings" "time" ) type ProductResponseSpec struct { Name string `json:"name"` Price int `json:"price"` CreatedAt time.Time `json:"created_at"` } type ProductResponseSpecProtect struct {..
-
[ Golang ] JSON Object 키 넣은 순서대로 정렬하기개발/golang 2021. 4. 2. 20:29
Golang 에서는 일반적인 JsonMarshal 을 통한 encoding 은 키순서 오름차순으로 encoding 이 되게끔 되어있다. 사실 Object 에는 키순서는 따로 중요하지 않지만 Object 키가 저장된 그대로 나와야하는 상황이 있으면 다음과 같은 로직이 필요하다. package order_json_object import ( "bytes" "encoding/json" ) type OrderJsonMap struct { Order []string Map map[string]string } func (om OrderJsonMap) MarshalJSON() ([]byte, error) { var b []byte buf := bytes.NewBuffer(b) buf.WriteRune('{') l :..
-
[ Golang ] Go 루틴 최대갯수를 제한하기개발/golang 2021. 4. 2. 00:11
DB 배치 작업을 하거나 외부 API 를 사용할때 커넥션 갯수가 너무 많아지는것이 부담스러울때 고루틴을 다음과 같이 제한 가능하다. package example_limit_gorutine import ( "fmt" "log" "sync" "time" ) func SelectTable(offset int) { time.Sleep(300 * time.Millisecond) log.Println(fmt.Sprintf("select * from table limit %d,10", offset)) } func Run(concurrentCount int, totalCount int) { concurrentGoroutines := make(chan struct{}, concurrentCount) var wg sync..
-
mariadb 에서 elasticsearch 실시간 연동하기개발/golang 2021. 3. 30. 14:46
개요 상품테이블과 상점테이블이 존재하고 두테이블 조인한 검색조건이 30개가 넘어감으로써 마땅한 인덱스를 찾기 어렵고검색시 속도 저하가 발생하여 실시간으로 elasticsearch 와 연동할수 있는 방법을 다음과 같이 구성함 구조 코드 1. binary 로그를 읽어 message queue 에 저장한다. import "github.com/siddontang/go-mysql/replication" var productAggregationPkMap = map[string]int{ "product": 0, "product_detail": 0, "product_memo": 1, } var shopAggregationPkMap = map[string]int{ "shop": 0, "shop_memo": 1, } fu..
-
[ Golang ] Go 루틴을 테스트 하기 (gomock)개발/golang 2021. 3. 11. 23:53
아래와 같은 크롤러가 있고 Mocking 하기위해서 HttpClient 라는 인터페이스를 만들어주었다. 아래 크롤러는 Http Status Code 가 200 이 나온값만 반환하는 로직이다. 실제 우리가 테스트할때에는 실제 Http 요청을 하면 아래 코드가 정상적으로 동작하는지 확인할수 없기때문에 다음과 같은 테스트 코드를 작성한다. type HttpClient interface { Request(url string, result chan HttpResponse) } type HttpResponse struct { StatusCode int Url string Body string } type Crawler struct { h HttpClient } func NewCrawler(h HttpClient) ..