要使用Go寫一個HTTP代理服務(wù)器,可以按照以下步驟進(jìn)行:
1. 導(dǎo)入必要的包:
```go
import (
"io"
"log"
"net"
"net/http"
)
```
2. 創(chuàng)建一個處理函數(shù)來處理HTTP請求并轉(zhuǎn)發(fā)請求到目標(biāo)服務(wù)器:
```go
func handler(w http.ResponseWriter, r *http.Request) {
// 建立與目標(biāo)服務(wù)器的連接
destConn, err := net.Dial("tcp", r.Host)
if err != nil {
log.Println(err)
http.Error(w, "Failed to connect to destination server.", http.StatusInternalServerError)
return
}
defer destConn.Close()
// 將請求發(fā)送到目標(biāo)服務(wù)器
err = r.Write(destConn)
if err != nil {
log.Println(err)
http.Error(w, "Failed to send request to destination server.", http.StatusInternalServerError)
return
}
// 將目標(biāo)服務(wù)器的響應(yīng)返回給客戶端
_, err = io.Copy(w, destConn)
if err != nil {
log.Println(err)
http.Error(w, "Failed to forward response from destination server.", http.StatusInternalServerError)
return
}
}
```
3. 創(chuàng)建一個HTTP服務(wù)器,并將請求轉(zhuǎn)發(fā)給處理函數(shù):
```go
func main() {
// 創(chuàng)建HTTP服務(wù)器
proxy := http.NewServeMux()
proxy.HandleFunc("/", handler)
// 監(jiān)聽端口
log.Println("Proxy server is running on port 8080...")
log.Fatal(http.ListenAndServe(":8080", proxy))
}
```
4. 運行程序,即可啟動一個HTTP代理服務(wù)器。
```shell
go run main.go
```
現(xiàn)在,你可以通過設(shè)置瀏覽器或其他應(yīng)用程序的代理服務(wù)器為`localhost:8080`來使用這個HTTP代理服務(wù)器。它將接收到的請求轉(zhuǎn)發(fā)到目標(biāo)服務(wù)器,并將目標(biāo)服務(wù)器的響應(yīng)返回給客戶端。