add real ip test

This commit is contained in:
fatedier
2021-06-21 19:27:26 +08:00
parent fe4e9b55f3
commit a51e221db3
6 changed files with 176 additions and 22 deletions

View File

@@ -1,6 +1,7 @@
package request
import (
"bufio"
"bytes"
"fmt"
"io"
@@ -120,7 +121,7 @@ func (r *Request) Do() (*Response, error) {
addr := net.JoinHostPort(r.addr, strconv.Itoa(r.port))
// for protocol http
if r.protocol == "http" {
return sendHTTPRequest(r.method, fmt.Sprintf("http://%s%s", addr, r.path),
return r.sendHTTPRequest(r.method, fmt.Sprintf("http://%s%s", addr, r.path),
r.host, r.headers, r.proxyURL, r.body)
}
@@ -151,7 +152,7 @@ func (r *Request) Do() (*Response, error) {
if r.timeout > 0 {
conn.SetDeadline(time.Now().Add(r.timeout))
}
buf, err := sendRequestByConn(conn, r.body)
buf, err := r.sendRequestByConn(conn, r.body)
if err != nil {
return nil, err
}
@@ -164,7 +165,7 @@ type Response struct {
Content []byte
}
func sendHTTPRequest(method, urlstr string, host string, headers map[string]string, proxy string, body []byte) (*Response, error) {
func (r *Request) sendHTTPRequest(method, urlstr string, host string, headers map[string]string, proxy string, body []byte) (*Response, error) {
var inBody io.Reader
if len(body) != 0 {
inBody = bytes.NewReader(body)
@@ -210,13 +211,18 @@ func sendHTTPRequest(method, urlstr string, host string, headers map[string]stri
return ret, nil
}
func sendRequestByConn(c net.Conn, content []byte) ([]byte, error) {
func (r *Request) sendRequestByConn(c net.Conn, content []byte) ([]byte, error) {
_, err := rpc.WriteBytes(c, content)
if err != nil {
return nil, fmt.Errorf("write error: %v", err)
}
buf, err := rpc.ReadBytes(c)
var reader io.Reader = c
if r.protocol == "udp" {
reader = bufio.NewReader(c)
}
buf, err := rpc.ReadBytes(reader)
if err != nil {
return nil, fmt.Errorf("read error: %v", err)
}

View File

@@ -1,7 +1,6 @@
package rpc
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
@@ -16,15 +15,12 @@ func WriteBytes(w io.Writer, buf []byte) (int, error) {
}
func ReadBytes(r io.Reader) ([]byte, error) {
// To compatible with UDP connection, use bufio reader here to avoid lost conent.
rd := bufio.NewReader(r)
var length int64
if err := binary.Read(rd, binary.BigEndian, &length); err != nil {
if err := binary.Read(r, binary.BigEndian, &length); err != nil {
return nil, err
}
buffer := make([]byte, length)
n, err := io.ReadFull(rd, buffer)
n, err := io.ReadFull(r, buffer)
if err != nil {
return nil, err
}