티스토리 뷰
Go를 이용한 HTTP Client 샘플코드
1. 심플한 요청 방법 ( Get Method )
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func Request(cgi string){
resp, _:= http.Get(cgi)
data, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Print(data)
}
func main(){
Request()
}
2. HTTP client를 생성하여 Request 하는 방법.
: Client를 생성하면 http에 필요한 여러가지 헤더정보 등을 추가하여 전송이 가능해진다.
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func Request(cgi string) []byte {
clnt := &http.Client{}
req, _ := http.NewRequest("GET", cgi, nil)
//req.Headder.Add([태그],[값]) 형태로 Header에 추가 정보를 추가 할 수 있음
//ex) Auth
//import에 "encoding/base64"추가 필요
//: req.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:1234")))
resp, _ := clnt.Do(req)
data, _ := ioutil.ReadAll(resp.Body)
fmt.Print(data)
resp.Body.Close()
//_ 는 erro 값인데 이를 처리하려면 _를 변수명으로 선언해주고 해당 값을 처리 하면된다.
return data
}
func main(){
Request("http://localhost:8080")
}
'Go' 카테고리의 다른 글
| Go - 간단한 Echo Server / Client (0) | 2021.08.31 |
|---|---|
| Go - Mac 설치 with VScode (0) | 2021.08.28 |
| Go - 설치하기(Windows10) (0) | 2021.08.27 |
댓글