본문 바로가기

프로그래밍/golang

[Golang] Proxy 환경 변수 http.ProxyFromEnvironment

 

대부분의 서비스는 어플리케이션이 직접 외부 인터넷과 통신하지 않습니다.

특히 회사 내부망, 보안망 등 환경에서는 주로 아래와 같은 구조를 사용합니다.

Application  <--->  Proxy Server  <--->  Internet

 

이러한 환경에서 서비스가 배포가 되며, 외부와 통신을 하려면 반드시 프록시 서버를 거치게 됩니다.

그래서 단순히 HTTP 요청만 구현하는 것이 아니라, 

  • 현재 환경에서 프록시를 사용하고 있는지
  • 어떤 요청은 프록시를 거치고, 어떤 것은 거치지 않는지
  • Proxy 운영 정책에 고려 사항이 있는지

를 함께 고려해야 합니다.

 

Golang에서는 표준 라이브러리 net/http에서 이를 통해서 기능을 제공하고 있습니다.

 

 

1. Proxy 환경변수

Golang의 http.ProxyFromEnvironment 에서 아래의 환경 변수를 자동으로 읽고 프록시 여부를 판단합니다.

 

  • HTTP_PROXY : http:// 요청에 사용 할 프록시
  • HTTPS_PROXY : https:// 요청에 사용할 프록시 
  • NO_PROXY : 프록시를 거치지 않을 대상 ( , 쉼표로 구분)
    • example.com : 해당 도메인 제외
    • .example.com  : 서브 도메인을 포함한 전체 도메인 제외
    • 192.168.1.0/24 : 특정 IP 대역 제외

 

2. 예제코드

 

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
)

func main() {
	setupEnv()
	defer cleanupEnv()

	transport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
	}

	targets := []string{
		"http://example.com",
		"http://localhost:8080",
		"http://openai.com",
		"http://google.com",
	}

	for _, target := range targets {
		printProxyDecision(transport, target)
	}
}

func setupEnv() {
	mustSetenv("HTTP_PROXY", "http://proxy.local:3128")
	mustSetenv("NO_PROXY", "example.com,localhost")
}

func cleanupEnv() {
	os.Unsetenv("HTTP_PROXY")
	os.Unsetenv("NO_PROXY")
}

func mustSetenv(key, value string) {
	if err := os.Setenv(key, value); err != nil {
		panic(err)
	}
}

func printProxyDecision(transport *http.Transport, target string) {
	req, err := http.NewRequest(http.MethodGet, target, nil)
	if err != nil {
		fmt.Printf("%-25s -> request error: %v\n", target, err)
		return
	}

	proxyURL, err := transport.Proxy(req)
	if err != nil {
		fmt.Printf("%-25s -> proxy error: %v\n", target, err)
		return
	}

	fmt.Printf("%-25s -> %s\n", target, formatProxy(proxyURL))
}

func formatProxy(proxyURL *url.URL) string {
	if proxyURL == nil {
		return "DIRECT"
	}
	return "PROXY: " + proxyURL.String()
}

 

 

3. 전체코드

https://github.com/reochoi109/go-handbook/blob/main/netadvanced/proxy_env/main.go

 

go-handbook/netadvanced/proxy_env/main.go at main · reochoi109/go-handbook

A personal handbook of Go patterns and best practices. Lightweight, practical code snippets for real-world backend development. - reochoi109/go-handbook

github.com