-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforward.go
More file actions
99 lines (84 loc) · 2.02 KB
/
Copy pathforward.go
File metadata and controls
99 lines (84 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"bytes"
"encoding/json"
// "errors"
"fmt"
"forwarder/read"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
type handle struct {
host string
port string
}
type normalHandle struct {
host string
port string
}
func (this *normalHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
remote, err := url.Parse("http://" + this.host + ":" + this.port)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.ServeHTTP(w, r)
}
func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
remote, err := url.Parse("http://" + this.host + ":" + this.port)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.ModifyResponse = modifyResp
proxy.ServeHTTP(w, r)
}
func modifyResp(resp *http.Response) error {
// 疑似这里已经被 read了。
origin := resp.Body
res, err := ioutil.ReadAll(origin)
defer origin.Close()
if err != nil {
return err
}
status := read.Status{}
err = json.Unmarshal(res, &status)
if err != nil {
fmt.Println("unmarshal failed")
fmt.Println("res", res)
return nil
}
fmt.Println("res", res)
// fmt.Printf("%s %v", "status", status)
s, err := json.Marshal(&status)
if err != nil {
return err
}
fmt.Println("marshalld ", string(s))
// fmt.Println("")
// in case content length does not match .There would be fatal error.
resp.Header["Content-Length"] = []string{}
// 找了半天就在找这个。 bytes.NewReader(s)将[]byte转成Reader. NopCloser将Reader转成ReadCloser.
resp.Body = ioutil.NopCloser(bytes.NewReader(s))
//
fmt.Println("response", resp)
// fmt.Println("resp.body", resp.Body)
// defer resp.Body.Close()
// defer origin.Close()
return nil
}
func startServer() {
//被代理的服务器host和port
h_temp := &handle{host: "192.168.0.75", port: "80"}
h_normal := &handle{host: "192.168.0.75", port: "80"}
err := http.ListenAndServe(":8888", h)
if err != nil {
log.Fatalln("ListenAndServe: ", err)
}
}
func main() {
startServer()
}