
344
러닝 Go
WithContext
메서드를 사용해야하는 또 다른 상황이 있는데, 당신의 응용 프로그램에서 다른
HTTP
서비스로
HTTP
호출을 만들 때이다. 미들웨어를 통해 컨텍스트를 전달하는 경우와 같
이
WithContext
를 사용하여 외부로 나가는 요청에 컨텍스트를 설정할 수 있다.
type ServiceCaller struct {
client *http.Client
}
func (sc ServiceCaller) callAnotherService(ctx context.Context, data string)
(string, error) {
req, err := http.NewRequest(http.MethodGet,
“http://example.com?data=”+data, nil)
if err != nil {
return “”, err
}
req = req.WithContext(ctx)
resp, err := sc.client.Do(req)
if err != nil {
return “”, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return “”, fmt.Errorf(“Unexpected status code %d”,
resp.StatusCode)
}
// ...