오늘은 환율을 받아오는 API 의 리턴 값인 JSON을 파싱하여 원하는 값을 가져오는 예제를 포스팅합니다.
인증키 없이 간단하게 받아오는 주소가 있어서 그 주소를 이용해서 일단 예제를 만들어 보았습니다.
https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD
위의 주소는 저도 웹에서 받은 것이라 안 될수도 있으니 주의해 주세요.
package common
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
_ "net/http"
_ "net/http/httputil"
_ "os"
)
type GetHTTPJSON []GetHTTPJSONElement
func UnmarshalGetHTTPJSON(data []byte) (GetHTTPJSON, error) {
var r GetHTTPJSON
err := json.Unmarshal(data, &r)
return r, err
}
func (r *GetHTTPJSON) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type GetHTTPJSONElement struct {
Code string `json:"code"`
CurrencyCode string `json:"currencyCode"`
CurrencyName string `json:"currencyName"`
Country string `json:"country"`
Name string `json:"name"`
Date string `json:"date"`
Time string `json:"time"`
RecurrenceCount int64 `json:"recurrenceCount"`
BasePrice float64 `json:"basePrice"`
OpeningPrice float64 `json:"openingPrice"`
HighPrice float64 `json:"highPrice"`
LowPrice float64 `json:"lowPrice"`
Change string `json:"change"`
ChangePrice float64 `json:"changePrice"`
CashBuyingPrice float64 `json:"cashBuyingPrice"`
CashSellingPrice float64 `json:"cashSellingPrice"`
TtBuyingPrice float64 `json:"ttBuyingPrice"`
TtSellingPrice float64 `json:"ttSellingPrice"`
TcBuyingPrice interface{} `json:"tcBuyingPrice"`
FcSellingPrice interface{} `json:"fcSellingPrice"`
ExchangeCommission float64 `json:"exchangeCommission"`
UsDollarRate float64 `json:"usDollarRate"`
High52WPrice float64 `json:"high52wPrice"`
High52WDate string `json:"high52wDate"`
Low52WPrice float64 `json:"low52wPrice"`
Low52WDate string `json:"low52wDate"`
CurrencyUnit int64 `json:"currencyUnit"`
Provider string `json:"provider"`
Timestamp int64 `json:"timestamp"`
ID int64 `json:"id"`
ModifiedAt string `json:"modifiedAt"`
CreatedAt string `json:"createdAt"`
ChangeRate float64 `json:"changeRate"`
SignedChangePrice float64 `json:"signedChangePrice"`
SignedChangeRate float64 `json:"signedChangeRate"`
}
func ConnectBank() {
resp, err := http.Get("https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWJPY")
if err != nil {
panic(err)
}
// finally resp closing 및 에러처리
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
// 결과 출력
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", string(data))
}
//엔화를 받아오는 함수
func ParsingJPY() float64 {
var f float64
res, err := http.Get("https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWJPY")
if err != nil {
panic(err)
fmt.Println("No response from request")
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
var (
result []GetHTTPJSONElement
)
if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to the go struct pointer
fmt.Println(err)
}
for i, _ := range result {
f = result[i].BasePrice
}
return f
}
환율을 받아오는 것을 struct 로 변환을 해주는 방법은 앞선 제 포스팅을 보시면
https://islet4you.tistory.com/entry/Flutter-Model-class-%EB%A7%8C%EB%93%A4%EC%96%B4%EC%A3%BC%EB%8A%94-%EC%82%AC%EC%9D%B4%ED%8A%B8
Flutter Model class 만들어주는 사이트
기록한다 기록한다하면서 오늘에서야 올립니다. 보통 우리는 API에서 데이터를 받아서 화면을 생성시켜줍니다. 이때 데이터에 대해서 Model을 만들고 함수를 만들어서 진행을 하는데요. 받은 json
islet4you.tistory.com
위의 포스팅을 보시면 받아오신 JSON을 붙여넣고 GO로 변환을 하시면 위의 소스에 있는 것처럼 struct 와 parsing 을 할 수 있는 함수를 자동으로 생성을 해준답니다.
역시나 언어는 프로젝트를 하면서 이해가 되는가 봅니다.
위의 예시에서 제일 헤깔렸던 부분은
var result []GetHTTPJSONElement 부분 이었습니다.
json배열형식인데 var 로 선언하고 받을려고 해서 오류가 있었답니다.
그리고 위의 함수도 리턴형태로 float64 로 리턴을 해줘서 소스에 있는
for i, _ := range result {
f = result[i].BasePrice
}
이 부분을 가지고 처리를 해줬습니다.
구조체(struct)내에서 제가 원하는 값만 가지고 오는 방법까지 소스를 보시면 잘 아실수 있을꺼에요.
오늘도 Go 언어에 대해서 하나씩 한걸음씩 알아가고 있습니다.
생각보다는 괜찮은 것 같습니다.
[Go Build] How to Go Build for linux (0) | 2022.07.13 |
---|---|
[GO]MAC zsh 에 GOPATH 설정하기 (0) | 2022.07.13 |
[go module] 폴더에 있는 모듈 선언하고 사용하는 방법 (0) | 2022.07.11 |
[Go] Scheduler 예제 (0) | 2022.07.06 |
go timer 예제코드 (0) | 2022.07.05 |