Skip to content

Commit

Permalink
Feat: rewritre http client with native string
Browse files Browse the repository at this point in the history
  • Loading branch information
PuerNya committed May 2, 2023
1 parent ed2d05a commit 7971b02
Showing 1 changed file with 33 additions and 22 deletions.
55 changes: 33 additions & 22 deletions protocol/http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
std_bufio "bufio"
"context"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"

"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
Expand Down Expand Up @@ -65,42 +66,52 @@ func (c *Client) DialContext(ctx context.Context, network string, destination M.
if err != nil {
return nil, err
}
request := &http.Request{
Method: http.MethodConnect,
URL: &url.URL{
Host: destination.String(),
},
Header: http.Header{
"Proxy-Connection": []string{"Keep-Alive"},
},
}
if c.path != "" {
err = URLSetPath(request.URL, c.path)
if err != nil {
return nil, err
}
URL := destination.String()
HeaderString := "CONNECT " + URL + " HTTP/1.0\r\n"
tempHeaders := map[string][]string{
"Host": {destination.String()},
"User-Agent": {"Go-http-client/1.1"},
"Proxy-Connection": {"Keep-Alive"},
}

for key, valueList := range c.headers {
request.Header.Set(key, valueList[0])
for _, value := range valueList[1:] {
request.Header.Add(key, value)
}
tempHeaders[key] = valueList
}

if c.path != "" {
tempHeaders["Path"] = []string{c.path}
}

if c.username != "" {
auth := c.username + ":" + c.password
request.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
if _, ok := tempHeaders["Proxy-Authorization"]; ok {
tempHeaders["Proxy-Authorization"][len(tempHeaders["Proxy-Authorization"])] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
} else {
tempHeaders["Proxy-Authorization"] = []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(auth))}
}
}
for key, valueList := range tempHeaders {
HeaderString += key + ": " + strings.Join(valueList, "; ") + "\r\n"
}
err = request.Write(conn)

HeaderString += "\r\n"

_, err = fmt.Fprintf(conn, "%s", HeaderString)

if err != nil {
conn.Close()
return nil, err
}

reader := std_bufio.NewReader(conn)
response, err := http.ReadResponse(reader, request)

response, err := http.ReadResponse(reader, nil)

if err != nil {
conn.Close()
return nil, err
}

if response.StatusCode == http.StatusOK {
if reader.Buffered() > 0 {
buffer := buf.NewSize(reader.Buffered())
Expand Down

0 comments on commit 7971b02

Please sign in to comment.