본문 바로가기
카테고리 없음

Go언어 HTTP 응답코드(Status) 출력 방법

by Warehaus 2023. 7. 5.

사진: UnsplashGlenn Carstens-Peters

 

2023.07.03 - [분류 전체보기] - go programming - strings.HasPrefix 사용

 

go programming - strings.HasPrefix 사용

사진: Unsplash의Glenn Carstens-Peters 2023.06.24 - [CS/Go] - [Go programming] Requesting http get method to an url from an argument [Go programming] Requesting http get method to an url from an argument 사진: Unsplash의Sergey Zolkin Today, I made a t

armin.tistory.com

 

 

이전 포스팅에 이어서 오늘은 http.Get 으로 부터 넘어오는

http status code를 출력해 보겠습니다.

 

일단 시작은 아래 코드로 진행해 봅니다.

 

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	for _, url := range os.Args[1:] {

		// Check http://
		// if url[0:7] != "http://" {
		// 	url = "http://" + url
		// }

		if !strings.HasPrefix(url, "http://") {
			url = "http://" + url
		}

		// 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)
		}
	}
}

 

http status code 는 resp  변수에 담겨 있습니다.

어떤 값들이 리턴되는지는 아래 Get함수의 명세를 보시면 알 수 있습니다.

 

https://pkg.go.dev/net/http#Get

 

http package - net/http - Go Packages

HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before. package main import ( "io" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *

pkg.go.dev

 

 

그럼 Get 함수에서 리턴받은 Response에는 어떤 값들이 들어있을까요?

아래 링크를 확인해 봅니다.

 

https://pkg.go.dev/net/http#Response

 

http package - net/http - Go Packages

HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before. package main import ( "io" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *

pkg.go.dev

 

링크 열어보기 귀찮으시면 아래 이미지만 확인하셔도 무방합니다.

 

 

 

 

 

 

 

 

Response 구조체에 Status 가 담겨있는 것을 알 수 있습니다.

그러면 앞에 예시 코드의 resp 에서 Status를 사용해 http 응답 코드를 출력해 보겠습니다.

 

코드는 다음과 같습니다.

resp.Status 를 fmt.Print 함수를 통해 출력하는 것을 보실 수 있습니다.

 

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	for _, url := range os.Args[1:] {
		if !strings.HasPrefix(url, "http://") {
			url = "http://" + url
		}

		// 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)
		}

		fmt.Print("Response code : ", resp.Status, "\n")

		// 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)
		}
	}
}

 

위 코드를 빌드하고 실행한 결과는 다음과 같습니다.

"Response code : 200 OK" 라는 http 응답 코드를 받음으로 서 정상적으로 응답을 수신함을 확인할 수 있습니다.

 

$ ./fetch google.com
Response code : 200 OK
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ko"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="9uu0q8y2thHKdKUFhuv22Q">(function(){var _g={kEI:'dj2kZLvVLcnqwQPa95SoAw',kEXPI:'0,1359409,6059,206,4804,2316,383,246,5,1129120,1197713,380778,16114,28684,22430,1362,284,12032,2819,14764,4998,17075,38444,889,1983,2891,4139,7615,606,29842,28445,2403,2614,13491,230,20583,4,1528,2304,42125,13660,4437,9357,13250,6630,7596,1,39047,2,3105,2,39761,5679,1021,31121,4568,6259,23418,1252,5835,19300,19,7465,445,2,2,1,6960,3997,13669,2006,8155,6682,699,15970,872,19634,7,1922,9779,12414,10479,15785,3781,20199,20136,14,82,1722,18484,3371,5006,18960,280,5123,3030,6110,9706,1804,10472,2884,450,19291,10958,43,2322,662,1635,3241,4707,5892,1146,8275,359,3079,7914,4951,5711,560,1517,3,3,9,1708,2421,1271,2041,372,1108,2,666,5209778,2,5993520,2804423,3311,141,795,19735,1,1,346,6945,12,23943527,579,2773241,1270287,14298,2375,2893,6250,19888,3919,2858,191,1403940,681642,23077628,994,2607,255,2465,549,2,1557,1972,928,448,1022,836,1545,16,5140,14,1246,1529,98,241,623,515,1079,1089,1791,650,437,119,543,629,81,1,573,297,451,670,345,804,1576,166,4,729,239,84,437,227,249,1284,4,870,311,482,168,46,1265,119,719,189,361,222,580,728,669,151,75,60,33,356,2,4,499,1501,732,27,786,129,395,9,107,3,75,186,167,188,680,33,132,71,128,975,47,206,169,7,212,1359,212,43,182,129,2,102,130,6,3,185,152,125,71,850,1845,194,535,745,64,358,1067,286,134',kBL:'VNBp',kOPI:89978449};(function(){var a;(null==(a=window.google)?0:a.stvsc)?google.kEI=_g.kEI:window.google=_g;}).call(this);})();(function(){google.sn='webhp';google.kHL='ko';})();(function(){
....

 

 

앞으로 http request를 go 언어에서 구현할 때마다

http response code 를 체크해야 할 일이 많을 것입니다.

 

그때마다 Status를 사용하여 정상적으로 응답을 수신하였는지 확인하면 되겠습니다.

 

 

 

wh.