• http内网转发


    package main
    
    import (
    	"io"
    	"log"
    	"net/http"
    	"strings"
    )
    
    func main() {
    	localHost := "127.0.0.1.8001"
    	targetHost := "127.0.0.1:80"
    	httpsServer(localHost, targetHost)
    
    	log.Fatalln("http server down!!!")
    }
    
    func httpsServer(addr string, remote_addr string) {
    
    	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    		cli := &http.Client{}
    		body := make([]byte, 0)
    		n, err := io.ReadFull(req.Body, body)
    		if err != nil {
    			io.WriteString(w, "Request Data Error")
    			return
    		}
    		reqUrl := "http://" + remote_addr + req.URL.Path
    
    		req2, err := http.NewRequest(req.Method, reqUrl, strings.NewReader(string(body)))
    		if err != nil {
    			io.WriteString(w, "Request Error")
    			return
    		}
    		// set request content type
    		contentType := req.Header.Get("Content-Type")
    		req2.Header.Set("Content-Type", contentType)
    		// request
    		rep2, err := cli.Do(req2)
    		if err != nil {
    			io.WriteString(w, "Not Found!")
    			return
    		}
    		defer rep2.Body.Close()
    		n, err = io.ReadFull(rep2.Body, body)
    		if err != nil {
    			io.WriteString(w, "Request Error")
    			return
    		}
    		// set response header
    		for k, v := range rep2.Header {
    			w.Header().Set(k, v[0])
    		}
    		io.WriteString(w, string(body[:n]))
    	})
    	var err error = nil
    	err = http.ListenAndServe(":12307", nil)
    	if err != nil {
    		log.Fatal("server down!!!")
    	}
    }
    

      

  • 相关阅读:
    设计模式—适配器模式
    设计模式—策略模式 状态模式
    设计模式——装饰模式和代理模式
    C++常考算法
    ModelState.AddModelError使用
    Json
    ref与out
    三层与mvc
    新的方法(Set<T>)实现mvc的crud
    【程序45】
  • 原文地址:https://www.cnblogs.com/saryli/p/11777534.html
Copyright © 2020-2023  润新知