0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go 言語を学ぶAdvent Calendar 2023

Day 24

IPアドレスを隠蔽したいので、GolangでHTTPプロキシサーバーを作る

Posted at

Goでプロキシサーバー

プロキシサーバーをGolangで作成してみます。

プロキシサーバー

ポート8080で作成します。リクエスト先のURLを取得し、代理でプロキシサーバーがリクエストを送信、レスポンスを複製して返しています。

main.go
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func handler(c echo.Context) error {
	url := c.Request().URL.String()
	req, _ := http.NewRequest(c.Request().Method, url, c.Request().Body)

	for name, values := range c.Request().Header {
		for _, value := range values {
			req.Header.Add(name, value)
		}
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return c.String(http.StatusInternalServerError, err.Error())
	}
	defer resp.Body.Close()
	fmt.Println(resp, "resp")

	for name, values := range resp.Header {
		for _, value := range values {
			c.Response().Header().Add(name, value)
		}
	}
	c.Response().WriteHeader(resp.StatusCode)
	io.Copy(c.Response(), resp.Body)
	return nil
}

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.GET("/", handler)
	log.Fatal(e.Start(":8080"))
}

ウェブサーバー

ポート8081でシンプルに文字列を返しています。

webserver/main.go
package main

import (
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})
	log.Fatal(e.Start(":8081"))
}

リクエスト送信プログラム

リクエスト先にlocalhost:8081のウェブサーバー、プロキシとしてlocalhost:8080のプロキシサーバーを指定

http_request.py
import requests

proxy = {"http": "http://localhost:8080"}


def get_request(url):
    r = requests.get(url, proxies=proxy)
    print(r.status_code)
    print(r.text)


if __name__ == "__main__":
    get_request("http://localhost:8081")

検証

全てを起動し、pythonプログラムを実行します。

$ python http_request.py
200
Hello, World!

プロキシサーバーのログ

$ go run main.go

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.11.4
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:8080
&{200 OK 200 HTTP/1.1 1 1 map[Content-Length:[13] Content-Type:[text/plain; charset=UTF-8] Date:[Mon, 25 Dec 2023 13:35:38 GMT]] 0x1400020a080 13 [] false false map[] 0x14000186200 <nil>} resp
{"time":"2023-12-25T22:35:38.926363+09:00","id":"","remote_ip":"::1","host":"localhost:8081","method":"GET","uri":"http://localhost:8081/","user_agent":"python-requests/2.31.0","status":200,"error":"","latency":2184250,"latency_human":"2.18425ms","bytes_in":0,"bytes_out":13}
$ go run webserver/main.go
   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.11.4
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:8081
{"time":"2023-12-25T22:32:35.058394+09:00","id":"","remote_ip":"::1","host":"localhost:8081","method":"GET","uri":"/","user_agent":"python-requests/2.31.0","status":200,"error":"","latency":1583,"latency_human":"1.583µs","bytes_in":0,"bytes_out":13}

よさそうです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?