Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

レガシー環境用のTLS1.2対応リバースプロキシを golang で簡単に作る

Last updated at Posted at 2020-12-18

はじめに

CentOS5 などのレガシーシステムでは TLS1.2 が利用できません。
OSバージョンアップや別サーバで Reverse Proxy を構築するのが一般的ですが結構な手間です。
そこで今回は、golang でちょちょいと TLS1.2 対応の Reverse Proxy を実装します。

やってみよう

必用なもの

  • golang v1.9以前(※ レガシーシステムではv1.9以前でコンパイルしないと動きません)

やりかた

golang ならわずか10行くらいのロジックでリバースプロキシができちゃいます。

main.go
package main

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

func main() {
	// プロキシしたいレガシーサーバのURL
	target, _ := url.Parse("http://localhost:80")
	// シングルホストの場合はこれだけでOK
	proxy := httputil.NewSingleHostReverseProxy(target)
	// ハンドラ内でヘッダーを設定してプロキシする
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		r.Header.Set(`X-Forwarded-Host`, r.Header.Get(`Host`))
		r.Header.Set(`X-Forwarded-Proto`, r.URL.Scheme)
		proxy.ServeHTTP(w, r)
	})

	// TLS1.2でListen
	err = http.ListenAndServeTLS(":443", "path to ssl cert", "path to ssl key", nil)
	if err != nil {
		log.Fatal(err)
	}
}

また、http.HandlerFunc()内では、以下のように Request Header も設定できます。
レガシーサーバ側が X-Forwarded-Proto などに対応していない場合は、Request をゴニョゴニョやって対応しましょう!

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		r.Header.Set(`X-Forwarded-Host`, r.Header.Get(`Host`))
		r.Header.Set(`X-Forwarded-Proto`, r.URL.Scheme)
		r.URL.Host = target.Host
		r.URL.Scheme = target.Scheme
		proxy.ServeHTTP(w, r)
	})

0
0
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?