윤준석

ADD: getItemsInfoByKeyword functions for handle api response

return apiResponse.Items slice
1 package service 1 package service
2 2
3 import ( 3 import (
4 - "fmt" 4 + "encoding/json"
5 + "io"
5 "io/ioutil" 6 "io/ioutil"
6 "joongna/config" 7 "joongna/config"
7 "joongna/model" 8 "joongna/model"
...@@ -15,11 +16,11 @@ func GetItemByKeyword(keyword string) ([]model.Item, error) { ...@@ -15,11 +16,11 @@ func GetItemByKeyword(keyword string) ([]model.Item, error) {
15 return items, nil 16 return items, nil
16 } 17 }
17 18
18 -func GetItemInfoByKeyword(keyword string) { 19 +func getItemsInfoByKeyword(keyword string) []model.ApiResponseItem {
19 encText := url.QueryEscape("중고나라" + keyword) 20 encText := url.QueryEscape("중고나라" + keyword)
20 - url := "https://openapi.naver.com/v1/search/cafearticle.json?query=" + encText + "&sort=sim" 21 + apiUrl := "https://openapi.naver.com/v1/search/cafearticle.json?query=" + encText + "&sort=sim"
21 22
22 - req, err := http.NewRequest("GET", url, nil) 23 + req, err := http.NewRequest("GET", apiUrl, nil)
23 if err != nil { 24 if err != nil {
24 log.Fatal(err) 25 log.Fatal(err)
25 } 26 }
...@@ -31,9 +32,18 @@ func GetItemInfoByKeyword(keyword string) { ...@@ -31,9 +32,18 @@ func GetItemInfoByKeyword(keyword string) {
31 if err != nil { 32 if err != nil {
32 log.Fatal(err) 33 log.Fatal(err)
33 } 34 }
34 - defer resp.Body.Close() 35 + defer func(Body io.ReadCloser) {
36 + err := Body.Close()
37 + if err != nil {
38 + log.Fatal(err)
39 + }
40 + }(resp.Body)
35 41
36 - bytes, _ := ioutil.ReadAll(resp.Body) 42 + response, _ := ioutil.ReadAll(resp.Body)
37 - str := string(bytes) 43 + var apiResponse model.ApiResponse
38 - fmt.Println(str) 44 + err = json.Unmarshal(response, &apiResponse)
45 + if err != nil {
46 + log.Fatal(err)
47 + }
48 + return apiResponse.Items
39 } 49 }
......