天天看點

golang 透明代理

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
)

type requestPayloadStruct struct {
	ProxyCondition string `json:"proxy_condition"`
}

// Get env var or default
func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}
	return fallback
}

// Get the port to listen on
func getListenAddress() string {
	port := getEnv("PORT", "8072")
	return ":" + port
}

// Serve a reverse proxy for a given url
func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {
	// parse the url
	url, err := url.Parse(target)
	if err != nil {
		fmt.Printf("err: %+v\n", err)
	}
	// create the reverse proxy
	proxy := httputil.NewSingleHostReverseProxy(url)

	// Update the headers to allow for SSL redirection
	req.URL.Host = url.Host
	req.URL.Scheme = url.Scheme
	req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
	req.Host = url.Host
        //web端,通過代理調該接口産生跨域問題,多個頭問題:
     //Access-Control-Allow-Origin' header contains multiple values '*, *'   删除一個頭
      //res.Header().Del("Access-Control-Allow-Origin") //如果産生上述問題,就删除一個頭
	// Note that ServeHttp is non blocking and uses a go routine under the hood
	proxy.ServeHTTP(res, req)
       
       //出現上述多個頭問題,删除頭操作,放在此處不起作用,
       //必須要放在proxy.ServeHTTP(res, req)操作前
       // res.Header().Del("Access-Control-Allow-Origin") 
}

// Get a json decoder for a given requests body
func requestBodyDecoder(request *http.Request) *json.Decoder {
	// Read body to buffer
	body, err := ioutil.ReadAll(request.Body)
	if err != nil {
		log.Printf("Error reading body: %v", err)
		panic(err)
	}

	// Because go lang is a pain in the ass if you read the body then any susequent calls
	// are unable to read the body again....
	request.Body = ioutil.NopCloser(bytes.NewBuffer(body))

	return json.NewDecoder(ioutil.NopCloser(bytes.NewBuffer(body)))
}

// Parse the requests body
func parseRequestBody(request *http.Request) requestPayloadStruct {
	decoder := requestBodyDecoder(request)

	var requestPayload requestPayloadStruct
	err := decoder.Decode(&requestPayload)

	if err != nil {
		panic(err)
	}

	return requestPayload
}

// Given a request send it to the appropriate url
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
	url := "http://50.73.65.35:8080"
	url = "http://192.168.1.221:8280/v2/facesets/search?page_size=10&page_number=0" //錯誤,代理的url為代理的接口所在的服務的IP和端口,而不是具體的接口的URL
	//url = "http://www.baidu.com"
	url = "http://192.168.1.240:11032" //正确示例,代理的url為代理服務接口位址+端口
	serveReverseProxy(url, res, req)
}

func main() {
	// start server
	http.HandleFunc("/", handleRequestAndRedirect)
	http.HandleFunc("/api/v4/login", handleRequestAndRedirect)
	err := http.ListenAndServe(getListenAddress(), nil)
	if err != nil {
		fmt.Println("err", err)
		panic(err)
	}
}
           

學藝不精,在做這個代理過程中遇到了問題,花了好久才解決問題,記錄在此,以備不時之需。