init
This commit is contained in:
56
examples/other/custom_delegate/custom_delegate.go
Normal file
56
examples/other/custom_delegate/custom_delegate.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/darkit/goproxy"
|
||||
)
|
||||
|
||||
// CustomDelegate 自定义委托
|
||||
type CustomDelegate struct {
|
||||
goproxy.DefaultDelegate
|
||||
}
|
||||
|
||||
// BeforeRequest 请求前事件
|
||||
func (d *CustomDelegate) BeforeRequest(ctx *goproxy.Context) {
|
||||
log.Printf("收到请求: %s %s\n", ctx.Req.Method, ctx.Req.URL.String())
|
||||
log.Printf("请求头: %v\n", ctx.Req.Header)
|
||||
}
|
||||
|
||||
// BeforeResponse 响应前事件
|
||||
func (d *CustomDelegate) BeforeResponse(ctx *goproxy.Context, resp *http.Response, err error) {
|
||||
if err != nil {
|
||||
log.Printf("响应错误: %v\n", err)
|
||||
return
|
||||
}
|
||||
log.Printf("收到响应: %d %s\n", resp.StatusCode, resp.Status)
|
||||
log.Printf("响应头: %v\n", resp.Header)
|
||||
}
|
||||
|
||||
// AfterResponse 响应后事件
|
||||
func (d *CustomDelegate) AfterResponse(ctx *goproxy.Context, resp *http.Response) {
|
||||
log.Printf("请求完成: %s %s, 耗时: %v\n",
|
||||
ctx.Req.Method,
|
||||
ctx.Req.URL.String(),
|
||||
time.Since(ctx.StartTime))
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 创建自定义委托
|
||||
delegate := &CustomDelegate{}
|
||||
|
||||
// 创建代理实例
|
||||
proxy := goproxy.NewProxy(
|
||||
goproxy.WithDelegate(delegate),
|
||||
goproxy.WithRequestTimeout(30*time.Second),
|
||||
goproxy.WithIdleTimeout(60*time.Second),
|
||||
)
|
||||
|
||||
// 启动代理服务器
|
||||
log.Println("自定义委托代理服务器启动在 :8080")
|
||||
if err := http.ListenAndServe(":8080", proxy); err != nil {
|
||||
log.Fatalf("代理服务器启动失败: %v", err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user