您现在的位置是:网站首页> Go语言

Go 实现简易https反代http服务

摘要

Go 实现简易https反代http服务

平时本地开了个临时的服务用于内网使用,很多都是http协议而且内容是明文传输的,我又是个懒人不想装个Nginx或者Apache专门开个反代,所以就弄个简易版的,如下:

生成自签名证书:

 openssl genrsa -out ./server.key

 openssl req -new -x509 -key ./server.key -out ./server.crt -days 365


Go代码

package main


import (

"flag"

"log"

"net/http"

"net/http/httputil"

"net/url"

"os"

)


var port = flag.String("p", "", "监听端口")

var targetUrl = flag.String("u", "", "目标url")


func main() {

flag.Parse()

if *port == "" || *targetUrl == "" {

os.Exit(0)

}


http.HandleFunc("/", ServeHTTP)

log.Fatal(http.ListenAndServeTLS("0.0.0.0:"+*port, "server.crt", "server.key", nil))

}


func ServeHTTP(w http.ResponseWriter, r *http.Request) {

remote, _ := url.Parse(*targetUrl)

proxy := httputil.NewSingleHostReverseProxy(remote)

proxy.ServeHTTP(w, r)

}

假设服务开在本地的8088端口,执行:

./main -p 4443 -u http://127.0.0.1:8088


浏览器访问

浏览器访问https://[自己的内网IP]:4443,信任自签名证书即可


Top