http get method 요청을 하고
response 내용을 stdout 으로 바로 출력하는 코드입니다.
요청을 보낼 url을 argument로 전달받는데,
이를 위해서 os 패키지의 Args 를 이용합니다.
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
for _, url := range os.Args[1:] {
// Request http get with given url from the first argument.
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}
// read body of response.
if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
fmt.Printf("Error: %s", err)
}
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading %s : %v\n", url, err)
os.Exit(1)
}
fmt.Printf("%s", b)
}
}
resp 의 내용인 resp.Body를 바로 stdout 으로 넣기 위해서는
io 패키지의 Copy 함수를 사용합니다.
Copy를 사용하지 않으려면 별도 버퍼에 넣었다가
fmt.Printf를 통해 stdout 으로 출력을 할 수도 있겠습니다.
그런데 이렇게 하는 경우 불필요한 메모리를 할당해야 하므로
표준출력만 필요한 경우에는 바로 io.Copy를 하는 것이 적절하다고 생각합니다.
위의 코드를 실행하면
아래와 같은 출력을 볼 수 있습니다.
http://www.tistory.com 을 argument 로 전달하여
get method 를 요청하고 이에 따른 결과를 stdout으로 출력하는 결과입니다.
$ ./http_get http://www.tistory.com
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta property="og:url" content="https://www.tistory.com">
<meta property="og:site_name" content="Tistory">
<meta property="og:title" content="Tistory">
<meta property="og:description" content="좀 아는 블로거들의 유용한 이야기">
<meta property="og:image" content="//t1.daumcdn.net/tistory_admin/static/images/openGraph/tistoryOpengraph.png">
<title>TISTORY</title>
<link rel="icon" href="https://t1.daumcdn.net/tistory_admin/favicon/tistory_favicon_32x32.ico" sizes="any">
<link rel="icon" type="image/svg+xml" href="https://t1.daumcdn.net/tistory_admin/top_v2/bi-tistory-favicon.svg" />
<link rel="apple-touch-icon" href="https://t1.daumcdn.net/tistory_admin/top_v2/tistory-apple-touch-favicon.png"> <link rel="stylesheet" type="text/css" href="//t1.daumcdn.net/tistory_admin/assets/tistory-web-top/1687148423/static/css/ext/swiper.min.css">
<link rel="stylesheet" type="text/css" href="//t1.daumcdn.net/tistory_admin/www/style/top/font.css">
<link rel="stylesheet" type="text/css" href="//t1.daumcdn.net/tistory_admin/assets/tistory-gnb/3.3.0/gnb.min.css">
<link rel="stylesheet" type="text/css" href="//t1.daumcdn.net/tistory_admin/assets/tistory-web-top/1687148423/static/css/pc/top.css">
<script type="text/javascript" src="https://developers.kakao.com/sdk/js/kakao.min.js" ></script>
<!--[if lt IE 9]>
....
body 의 내용이 너무 많기에 적당히 내용을 짤랐습니다.
warehouse.