simple http handler

addon-dailer
lqqyt2423 4 years ago
parent cfa1b0eeaa
commit c3ed4478d9

@ -0,0 +1,6 @@
# go-mitmproxy
## TODO
- [x] http handler
- [ ] https handler

@ -1,8 +1,11 @@
package main package main
import proxy "github.com/lqqyt2423/go-mitmproxy" import (
"log"
proxy "github.com/lqqyt2423/go-mitmproxy"
)
func main() { func main() {
proxy.Create() log.Fatal(proxy.NewProxy().Start())
proxy.Init()
} }

@ -7,11 +7,22 @@ import (
"time" "time"
) )
func Create() { type Proxy struct {
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { Server *http.Server
}
func (proxy *Proxy) Start() error {
log.Printf("Proxy start listen at :8080")
return proxy.Server.ListenAndServe()
}
func (proxy *Proxy) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if !req.URL.IsAbs() || req.URL.Host == "" { if !req.URL.IsAbs() || req.URL.Host == "" {
res.WriteHeader(400) res.WriteHeader(400)
io.WriteString(res, "此为代理服务器,不能直接发起请求") _, err := io.WriteString(res, "此为代理服务器,不能直接发起请求")
if err != nil {
log.Printf("error: %v", err)
}
return return
} }
@ -24,19 +35,31 @@ func Create() {
proxyReq.Header[key] = value proxyReq.Header[key] = value
} }
proxyRes, _ := http.DefaultClient.Do(proxyReq) proxyRes, _ := http.DefaultClient.Do(proxyReq)
defer proxyRes.Body.Close()
for key, value := range proxyRes.Header { for key, value := range proxyRes.Header {
res.Header()[key] = value res.Header()[key] = value
} }
res.WriteHeader(proxyRes.StatusCode) res.WriteHeader(proxyRes.StatusCode)
io.Copy(res, proxyRes.Body) _, err := io.Copy(res, proxyRes.Body)
if err != nil {
log.Printf("error: %v", err)
return
}
log.Printf("%v %v %v - %v ms", req.Method, req.URL.String(), proxyRes.StatusCode, time.Since(start)) err = proxyRes.Body.Close()
}) if err != nil {
log.Printf("error: %v", err)
return
} }
func Init() { log.Printf("%v %v %v - %v ms", req.Method, req.URL.String(), proxyRes.StatusCode, time.Since(start).Milliseconds())
log.Println("server begin listen at :8000") }
log.Fatal(http.ListenAndServe(":8000", nil))
func NewProxy() *Proxy {
proxy := new(Proxy)
proxy.Server = &http.Server{
Addr: ":8080",
Handler: proxy,
}
return proxy
} }

Loading…
Cancel
Save