함수 getHTTPCode()

함수 getHTTPCode()
함수 get_http_code()

1 Bash[ | ]

curl -s -o /dev/null -w '%{http_code}' 'not-url' # 000
echo
curl -s -o /dev/null -w '%{http_code}' 'https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/not-exist' # 404
echo
curl -s -o /dev/null -w '%{http_code}' 'https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/.go-version' # 200

2 Go[ | ]

package main

import (
	"fmt"
	"net/http"
)

func getHTTPCode(url string) int {
	resp, err := http.Get(url)
	if err != nil {
		return 0
	}
	return resp.StatusCode
}

func main() {
	fmt.Println(getHTTPCode("not-url"))                                                                     // 0
	fmt.Println(getHTTPCode("https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/not-exist"))   // 404
	fmt.Println(getHTTPCode("https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/.go-version")) // 200
}

3 PHP[ | ]

function get_http_code($url) {
	if(filter_var($url, FILTER_VALIDATE_URL) === false) return false;
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_NOBODY, true); 
	curl_exec($ch);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	return $http_code;
}
var_dump( get_http_code("not-url") ); // bool(false)
var_dump( get_http_code('https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/not-exist') ); // int(404)
var_dump( get_http_code('https://raw.githubusercontent.com/kubernetes/kubernetes/v1.26.3/.go-version') ); // int(200)

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}