frp/test/e2e/pkg/request/request.go

41 lines
952 B
Go
Raw Normal View History

2020-06-02 16:48:55 +02:00
package request
import (
"fmt"
"net"
"time"
)
2020-09-07 08:57:23 +02:00
func SendTCPRequest(port int, content []byte, timeout time.Duration) (string, error) {
2020-06-02 16:48:55 +02:00
c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
2020-09-07 08:57:23 +02:00
return "", fmt.Errorf("connect to tcp server error: %v", err)
2020-06-02 16:48:55 +02:00
}
defer c.Close()
c.SetDeadline(time.Now().Add(timeout))
2020-09-07 08:57:23 +02:00
return sendRequestByConn(c, content)
2020-06-02 16:48:55 +02:00
}
2020-09-07 08:57:23 +02:00
func SendUDPRequest(port int, content []byte, timeout time.Duration) (string, error) {
c, err := net.Dial("udp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return "", fmt.Errorf("connect to udp server error: %v", err)
}
defer c.Close()
c.SetDeadline(time.Now().Add(timeout))
return sendRequestByConn(c, content)
}
func sendRequestByConn(c net.Conn, content []byte) (string, error) {
2020-06-02 16:48:55 +02:00
c.Write(content)
buf := make([]byte, 2048)
2020-09-07 08:57:23 +02:00
n, err := c.Read(buf)
if err != nil {
return "", fmt.Errorf("read error: %v", err)
2020-06-02 16:48:55 +02:00
}
return string(buf[:n]), nil
}