zoukankan      html  css  js  c++  java
  • Go net/http代理

    share/share.go

    /******
    ** @创建时间 : 2020/5/25 20:26
    ** @作者 : SongZhiBin
    ******/
    package share
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    	"net/url"
    	"os"
    )
    
    // ========= global variable
    var Config conf
    var LogOut *os.File
    
    // ========== Struct
    type conf struct {
    	TargetIP   string
    	TargetPort int
    	LocalPort  int
    }
    
    // 转发中间件
    func (c *conf) Forward(w http.ResponseWriter, r *http.Request) {
    	u, _ := url.Parse(fmt.Sprintf("http://%s:%d/", Config.TargetIP, Config.TargetPort))
    	proxy := httputil.NewSingleHostReverseProxy(u)
    	proxy.ServeHTTP(w, r)
    }
    

      

    config.txt

    [target]
    TargetIP = 127.0.0.1
    TargetPort = 8080
    LocalPort = 80
    

     

    run.go 

    /******
    ** @创建时间 : 2020/5/25 19:09
    ** @作者 : SongZhiBin
    ******/
    package main
    
    import (
    	"fmt"
    	"gopkg.in/ini.v1"
    	"net/http"
    	"os"
    )
    import "Songzhibin/HttpAgent/share"
    
    func main() {
    	// 读取配置文件
    	share.LogOut = os.Stdout
    	cfg, err := ini.Load("./config.txt")
    	if err != nil {
    		// 读取失败,使用默认配置
    		share.Config.TargetIP = "127.0.0.1"
    		share.Config.TargetPort = 80
    		share.Config.LocalPort = 80
    		fmt.Fprintf(share.LogOut, "使用默认配置->TargetIP:%s TargetPort:%d
    ", share.Config.TargetIP, share.Config.TargetPort)
    	}
    
    	err = cfg.Section("target").MapTo(&share.Config)
    	if err != nil {
    		fmt.Fprintf(share.LogOut, "MapTo映射失败->Err:%s
    ", err)
    		return
    	}
    	fmt.Fprintf(share.LogOut, "配置文件启动->TargetIP:%s TargetPort:%d
    ", share.Config.TargetIP, share.Config.TargetPort)
    	http.HandleFunc("/", share.Config.Forward)                                 // 设置默认路由
    	err = http.ListenAndServe(fmt.Sprintf(":%d", share.Config.LocalPort), nil) 
    	if err != nil {
    		fmt.Printf("http server failed, err:%v
    ", err)
    		return
    	}
    }
    

      

    Songzhibin
  • 相关阅读:
    Fault-Tolerant Virtual Machine 论文笔记
    Google File System 论文笔记
    Amazon Aurora 论文笔记
    MATLAB入门学习(二):分支语句和编程设计
    MATLAB入门学习(一):基础准备
    矩阵连乘问题
    合并排序 java
    生产者与消费者 代码实现 java
    图的封装(C++)
    二叉树的封装
  • 原文地址:https://www.cnblogs.com/binHome/p/12965164.html
Copyright © 2011-2022 走看看