[go] net/http 패키지를 사용한 기본 인증 처리
Go 언어의 net/http
패키지를 사용하면 HTTP 요청에 대한 기본 인증을 간단하게 처리할 수 있습니다. 기본 인증은 사용자 이름과 비밀번호를 요청 헤더에 포함하여 서버에 요청을 보내는 방식입니다.
요청에 기본 인증 정보 추가
HTTP 요청을 보낼 때 username:password
를 base64로 인코딩하여 Authorization
헤더에 추가합니다.
다음은 기본 인증 정보를 포함한 GET 요청을 보내는 예제 코드입니다.
package main
import (
"fmt"
"net/http"
"encoding/base64"
)
func main() {
username := "username"
password := "password"
url := "https://api.example.com/data"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
auth := username + ":" + password
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Set("Authorization", basicAuth)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Response Status:", resp.Status)
}
요청 실패 및 에러 처리
인증 정보가 잘못된 경우나 서버에서 인증을 거부할 경우를 대비하여 적절한 에러 처리를 해주어야 합니다.
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
fmt.Println("Authentication failed")
} else if resp.StatusCode != http.StatusOK {
fmt.Println("Request failed with status:", resp.Status)
}
결론
Go의 net/http
패키지를 사용하여 기본 인증 정보를 포함한 HTTP 요청을 보내는 방법에 대해 알아보았습니다. 이를 통해 안전한 방법으로 웹 서비스에 요청을 보낼 수 있습니다.