PHpullh
학습 라이브러리/Go/API 게이트웨이 패턴

GO · 패턴

API 게이트웨이 패턴

여러 마이크로서비스에 대한 단일 진입점. 라우팅, 인증, 속도 제한을 처리합니다.

패턴고급api-gatewayreverse-proxyroutingmicroservice

핵심 설명

여러 마이크로서비스에 대한 단일 진입점. 라우팅, 인증, 속도 제한을 처리합니다.

Go code

package main

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

type Route struct {
	Path   string
	Target string
}

type Gateway struct {
	routes []Route
	mux    *http.ServeMux
}

func NewGateway(routes []Route) *Gateway {
	gw := &Gateway{routes: routes, mux: http.NewServeMux()}

	for _, route := range routes {
		target, _ := url.Parse(route.Target)
		proxy := httputil.NewSingleHostReverseProxy(target)

		path := route.Path
		gw.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[GW] %s %s → %s\n", r.Method, r.URL.Path, target)
			proxy.ServeHTTP(w, r)
		})
	}
	return gw
}

func (gw *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	gw.mux.ServeHTTP(w, r)
}

func main() {
	routes := []Route{
		{Path: "/api/users/", Target: "http://localhost:8081"},
		{Path: "/api/orders/", Target: "http://localhost:8082"},
		{Path: "/api/products/", Target: "http://localhost:8083"},
	}
	gw := NewGateway(routes)
	fmt.Println("게이트웨이 라우팅:")
	for _, r := range routes {
		fmt.Printf("  %s → %s\n", r.Path, r.Target)
	}
	_ = gw
}

학습 팁

httputil.ReverseProxy는 Go 표준 라이브러리의 리버스 프록시입니다. 커스텀 헤더 추가, 요청 수정 등이 가능합니다.

주의할 점

게이트웨이에 비즈니스 로직을 넣으면 단일 장애점이 됩니다. 라우팅, 인증, 속도 제한만 담당하세요.

자주 묻는 질문

API 게이트웨이 패턴란 무엇인가요?

여러 마이크로서비스에 대한 단일 진입점. 라우팅, 인증, 속도 제한을 처리합니다.

API 게이트웨이 패턴 학습 시 주의할 점은 무엇인가요?

게이트웨이에 비즈니스 로직을 넣으면 단일 장애점이 됩니다. 라우팅, 인증, 속도 제한만 담당하세요.