花名/ID: 天析

邮箱: 2200475850@qq.com

主攻方向: 物联网安全、WEB安全

兴趣爱好: 乒乓球、羽毛球、排球、业余无线电···

备案信息:蜀ICP备19023334号

Golabg Web 编程之编写一个简单的端口转发服务

因为最近在写一些功能的时候,需要转发某接口来做到保护源站服务接口的目的,于是采用了 GO 作为后端语言,这里只给出简单的转发demo,你可以在参考我的代码后,在其基础上编写一些其他功能

Golang发起get请求

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func cx_api(question string) {

    url := "http://xxx.xxx.xxx/api.php?&question=" + question
    method := "GET"
    client := &http.Client{}
    req, err := http.NewRequest(method, url, nil)
    if err != nil {
        fmt.Println(err)
    }
    res, err := client.Do(req)
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    fmt.Println(string(body))

}

func main() {
    cx_api("xxxxxxxx")
}

套入Web接收GET并转发

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "time"
)

// index
func index(w http.ResponseWriter, r *http.Request) { //根目录

    t := time.Now().UTC().Format(time.UnixDate)

    logo := `
     _______                            _________
    (  ____ \|\     /||\     /||\     /|\__   __/
    | (    \/( \   / )( \   / )( \   / )   ) (   
    | |       \ (_) /  \ (_) /  \ (_) /    | |   
    | |        ) _ (    ) _ (    ) _ (     | |   
    | |       / ( ) \  / ( ) \  / ( ) \    | |   
    | (____/\( /   \ )( /   \ )( /   \ )   | |   
    (_______/|/     \||/     \||/     \|   )_(   

    后端:Golang

    查询接口:/cx?question={con}

    `

    fmt.Fprintf(w, "\n\t[ api ]\t"+t+"\n")

    fmt.Fprintf(w, logo)
}

// cx
func get(w http.ResponseWriter, request *http.Request) {
    question := request.FormValue("question")

    url := "http://xxx.xxx.xxx/api.php?question=" + question
    method := "GET"
    client := &http.Client{}
    req, err := http.NewRequest(method, url, nil)
    if err != nil {
        fmt.Println(err)
    }
    res, err := client.Do(req)
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    con := string(body)
    fmt.Fprintln(w, fmt.Sprintf("%s", con))

}

func main() {

    fmt.Println("\n\t状态:接口转发启动成功!\t端口:5005\n")

    // 路由控制
    http.HandleFunc("/", index)
    http.HandleFunc("/cx", get)

    //监听控制
    err := http.ListenAndServe(":5005", nil)
    if err != nil {
        log.Fatal("监听: ", err)
    }
}