This commit is contained in:
Владимир Федоров
2025-07-20 04:44:00 +07:00
parent 3cfa44b99c
commit 729015c4ea
7 changed files with 85 additions and 51 deletions
+24 -39
View File
@@ -2,10 +2,9 @@ package http
import (
"bufio"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
)
@@ -15,7 +14,14 @@ var (
SP = []byte(" ")
)
func Do(method string, url string, headers []*Header) (*Response, error) {
func getIP(domain string) string {
if domain == "test.ru" {
return "127.0.0.1:8081"
}
return ""
}
func Do(method string, url string, headers []Header) (*Response, error) {
url = strings.TrimPrefix(url, "http://")
url = strings.TrimPrefix(url, "https://")
path := "/"
@@ -27,48 +33,27 @@ func Do(method string, url string, headers []*Header) (*Response, error) {
path = "/" + path
}
connectPath := arr[0]
// conn, err := net.Dial("tcp", connectPath)
conn, err := tls.Dial("tcp", connectPath, nil)
connectPath := getIP(arr[0])
conn, err := net.Dial("tcp", connectPath)
// conn, err := tls.Dial("tcp", connectPath, nil)
if err != nil {
return nil, errors.New("connect " + connectPath)
}
defer conn.Close()
WriteRequest(conn, method, arr[0], path, "HTTP/1.0", headers)
DebugWrap(
conn,
&Request{
Method: method,
Path: path,
Protocol: "HTTP/1.0",
Headers: headers,
},
WriteRequest,
)
return ReadResponse(conn)
}
func WriteRequest(
w io.Writer,
method string,
host string,
path string,
httpVersion string,
headers []*Header,
) {
io.WriteString(w, method)
w.Write(SP)
io.WriteString(w, path)
w.Write(SP)
io.WriteString(w, httpVersion)
w.Write(CRLF)
for _, header := range headers {
WriteHeader(w, header.Name, header.Value)
}
// headers end
w.Write(CRLF)
// todo: body
}
func WriteHeader(w io.Writer, name string, value string) {
fmt.Fprintf(w, "%s:%s", name, value)
w.Write(CRLF)
}
func ReadResponse(r io.Reader) (*Response, error) {
b := bufio.NewReader(r)
@@ -93,7 +78,7 @@ func ReadResponse(r io.Reader) (*Response, error) {
headerStr := ""
contentLengthStr := ""
headers := []*Header{}
headers := []Header{}
for {
headerStr, err = b.ReadString('\n')
if err != nil {
@@ -104,7 +89,7 @@ func ReadResponse(r io.Reader) (*Response, error) {
}
arr := strings.Split(headerStr, ": ")
value := strings.TrimSpace(arr[1])
header := &Header{Name: arr[0], Value: value}
header := Header{Name: arr[0], Value: value}
if header.Name == "Content-Length" {
contentLengthStr = header.Value
}