【发布时间】:2021-07-16 14:05:02
【问题描述】:
我想为此实现一个HTTP请求和响应系统
client ------> A ----------> B --------> (request) HTTPserver
client <------ A <---------- B <-------- (response) HTTPserver
- 客户端使用任何 HTTP 方法(POST、PUT 等)向 A 发送 HTTP 请求
- A 然后读取请求正文加密它,然后将其转发给 B 3 B 然后解密读取的HTTP请求正文
- B 然后将接收到的解密正文作为有效负载准备 HTTP 请求并发送到 HTTP 服务器。 5 HTTP 服务器然后响应 B。
- B 然后加密来自 HTTP 服务器的响应,然后转发给 A。
- A 还解密来自 B 的响应,然后将响应发送回客户端。
我已经根据之前的建议实现了以下内容。
ProxyA:
const (
ServerB = "<address of B>"
Port = "<proxy A port>"
)
func main() {
// start server
http.HandleFunc("/", proxyPass)
log.Fatal(http.ListenAndServe(":" + Port, nil))
}
func proxyPass(res http.ResponseWriter, req *http.Request) {
// read request body from client
bodybytes, _ := ioutil.ReadAll(req.Body)
defer req.Body.Close()
// encrypt req.Body
object, _ := enc.Encrypt(bodybytes)
// serialize object
serialized, _ := object.CompactSerialize()
// prepare forwarding message
msg := message{reformatedData: serialized}
// encode message
msgbytes, _ := json.Marshal(&msg)
req.ContentLength = int64(len(msgbytes))
req.Body = ioutil.NopCloser(bytes.NewBuffer(msgbytes))
// How do I read the response data from proxy server B and then send
// response to the client
....
url, _ := url.Parse(ServerB)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(res, req)
}
For proxy B:
const (
Server = "<address of server>"
Port = "<proxy B port>"
)
func main() {
// start server
http.HandleFunc("/", proxyPass)
log.Fatal(http.ListenAndServe(":" + Port, nil))
}
func proxyPass(res http.ResponseWriter, req *http.Request) {
var msg message
HTTPServerurl := http://xxxxx
// read request body
bodybytes, _ := ioutil.ReadAll(req.Body)
req.ContentLength = int64(len(bodybytes))
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodybytes))
// decode message
err = json.Unmarshal(bodybytes, &msg)
// decrypt message
object, _ := jose.ParseEncrypted(msg)
decrypted, _ := object.Decrypt("phrasetodecryptmessage")
//send HTTP request to HTTP server
resp, _ := HandlemessageToHTTPServer(decrypted, "POST", HTTPServerurl)
//read response body
RespBody, _ := ioutil.ReadAll(resp.Body)
// encrypt response body
object, _ = enc.Encrypt(producerRespBody)
serialized, _ := object.CompactSerialize()
// prepare response JSON message
resmsg := resmessage {resmessage: serialized}
// marshall response message
respmsgbytes, _ := json.Marshal(&resmsg)
// How do I write the "respmsgbytes" to proxyServHTTP "res" back to proxy A
url, _ := url.Parse(Server)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(res, req)
}
我的问题是
-
如何将代理B中的“respmsgbytes”写入proxyServHTTP“res”返回代理A?
-
如何从代理服务器 B 读取响应数据然后发送 回复客户?
有什么帮助吗?我留下了错误检查以使代码简短。
【问题讨论】:
-
您可能会发现 stdlib
httputil.ReverseProxy很有用