golang 에서는 일반적인 url 호출 에는 net/http 패키지가 있다
curl https://api.example.com/surprise \
-u banana:coconuts \
-d "sample data"
Go
x
22
22
1
// Generated by curl-to-Go: https://mholt.github.io/curl-to-go
2
3
// curl https://api.example.com/surprise \
4
// -u banana:coconuts \
5
// -d "sample data"
6
7
params := url.Values{}
8
params.Add("sample data", ``)
9
body := strings.NewReader(params.Encode())
10
11
req, err := http.NewRequest("POST", "https://api.example.com/surprise", body)
12
if err != nil {
13
// handle err
14
}
15
req.SetBasicAuth("banana", "coconuts")
16
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
17
18
resp, err := http.DefaultClient.Do(req)
19
if err != nil {
20
// handle err
21
}
22
defer resp.Body.Close()
위와 같은 방식의 curl 을 호출하는 net.http 패키지를 이용한 request 코드는 위와 같다
이 코드는 curl 명령을 그대로 golang 코드로 바꾸어주는 https://mholt.github.io/curl-to-go/ 사이트를 이용해나온 코드이다
다른 방법으로
이보다 심플하게 request 코드를 구성할 수 있는데
decorate 패턴을 이용해 구현된 go resty 라는 패키지 이다
https://github.com/go-resty/resty
Go
1
9
1
import "github.com/go-resty/resty/v2"
2
3
4
client := resty.New()
5
resp, err := client.R().
6
SetBody(jsonvar).
7
SetResult(AuthSuccess{}). // or SetResult(AuthSuccess{}).
8
SetError(&AuthError{}). // or SetError(AuthError{}).
9
Post("http://url/url/url")
body 에 json 변수를 넣었고 해당 변수에 들어간 타입에 따라 자동으로 mime 타입이 결정
json 에 대한 마샬링/언마샬링을 자동으로 해준다..
자세한 내용은 위 링크를 통해 확인가능하다
댓글 남기기