因为最近在写一些功能的时候,需要转发某接口来做到保护源站服务接口的目的,于是采用了 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)
}
}