yehey's 공부 노트 \n ο(=•ω<=)ρ⌒☆

[golang] http response unmarshal (with type struct) 본문

개발/Golang

[golang] http response unmarshal (with type struct)

yehey 2023. 10. 31. 21:49

golang으로 request 보내기

request, err:= http.NewRequest("METHOD","URL",body io.Reader)

if err!=nil{
    fmt.Println(err)
    return err
}

//이후에 Request를 더 커스텀 할 수 있음
request.Header.Set("KEY","Value")

//request 전송, 응답 확인
client:=&http.Client{}

response,err:=client.Do(request)

if err!=nil{
    fmt.Println(err)
    return err
}
defer response.Body.Close()

//응답 데이터 일반 string 출력

data,err:=ioutil.ReadAll(response.Body)

if err!=nil{
    fmt.Println(err)
    return err
}

fmt.Printf("%s\n",string(data))

여기까지는 일반적인 golang http request 날리고 response 받는 방법

근데 내가 하고 싶었던건 response를 받으면 그걸 객체로 사용하는거…

아무리 찾아도 없다가 하나 찾은 방법은 좀 귀찮은 방법이었다.

그치만..이거 말고는 찾을 수 없었으니 써야만했음…

어차피 결과값은 다 json으로 오기 때문에 []bytejson 으로 unmarshal (언마샬링)해주면 된다.

근데 사실 마샬링,언마샬링 차이를 확실히 아는건 아니라서..

지금까지 찾아본 결과로는

 

 

이렇다고 한다.

 

나는 Json 텍스트로 온 response를 go 자료형으로 변환해서 입맛대로 파싱해서 사용하고 싶었던거기 때문에..

unmarshal을 진행한다.

 

근데 unmarshal의 2번째 인자는 go 언어 자료형을 담을 변수의 주소값이어야한다. 그래야 해당 변수에 잘 담겨서 사용하니까.

문제는 그 변수의 type인데, 이게 json 텍스트랑 어느정도 잘 맞아야한다는것…

사실 어느정도가 아니라 걍 잘 맞아야한다.

그래서 하나하나 만들어도 되지만..?

https://mholt.github.io/json-to-go/

 

JSON-to-Go: Convert JSON to Go instantly

This tool instantly converts JSON into a Go type definition. Paste a JSON structure on the left and the equivalent Go type will be generated to the right, which you can paste into your program. The script has to make some assumptions, so double-check the o

mholt.github.io

여기에 들어가서 postman 결과값을 넣는 선택을 했다.

그러면 필요한 type 구조체가 반환된다.

그래서 unmarshal 한 코드를 다시 보면

//응답 데이터 일반 string 출력

data,err:=ioutil.ReadAll(response.Body)

if err!=nil{
    fmt.Println(err)
    return err
}

type ResTest struct {
    URL          string `json:"url"`
    Test          string `json:"test"`
}

var test ResTest

if err:= json.Unmarshal(data, &test);err!=nil{
    fmt.Println("Cannot unmarshal json")
}
fmt.Println(test) // 이제 test를 이용해서 response body를 go 객체처럼 사용할 수 잇다!!

아니 근데 해결책을 찾긴 햇는데 맨날 type struct하는거 개오바라고 생각함

 

golang으로 POST request 보내기

Request body 가 필요한 경우에는 다음과 같이 만들어서 marshal 진행했다.

var jsonBody = map[string]interface{}{
	"role":   configs.Config.RoleID,
	"secret": configs.Config.SecretID,
}
jbytes, _ := json.Marshal(jsonBody)

request, err := http.NewRequest("POST", "URL", bytes.NewBuffer(jbytes))
if err != nil {
	MyLogger.Error.Println("HTTP 요청 생성 실패")
	return "", err
}
request.Header.Add("Content-type", "application/json")

아무리 생각해도 비효율이라고 생각하지만 플젝 진행하면서 더 나은 방법은 찾지 못했다.

자주 사용하는 객체는 타입 미리 생성하고 호출하는 작업만 추가해줬다.

'개발 > Golang' 카테고리의 다른 글

[golang] 기본 문법 및 함수  (1) 2023.11.19
[golang] logger 추가하기, custom logger 생성하기  (1) 2023.11.02
Comments