diff options
| author | Ho3ein <ho3ein.sanaei@gmail.com> | 2023-05-22 10:56:14 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-05-22 10:56:14 +0300 |
| commit | 5f489c3d08b36c9569fa67f0c5bf46be8ada7b21 (patch) | |
| tree | 0241a998df1f52f5170aec9bc263414e8a2a3e96 /web/network/auto_https_conn.go | |
| parent | 3d712890753a4f9981cca95685dec7ad4fff0acf (diff) | |
| parent | f82d0051b2cf827228b5c939d22622bd0d066149 (diff) | |
Merge pull request #491 from hamid-gh98/main
[tgbot] Multi language + More...
Diffstat (limited to 'web/network/auto_https_conn.go')
| -rw-r--r-- | web/network/auto_https_conn.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/web/network/auto_https_conn.go b/web/network/auto_https_conn.go new file mode 100644 index 00000000..d1a9d521 --- /dev/null +++ b/web/network/auto_https_conn.go @@ -0,0 +1,67 @@ +package network + +import ( + "bufio" + "bytes" + "fmt" + "net" + "net/http" + "sync" +) + +type AutoHttpsConn struct { + net.Conn + + firstBuf []byte + bufStart int + + readRequestOnce sync.Once +} + +func NewAutoHttpsConn(conn net.Conn) net.Conn { + return &AutoHttpsConn{ + Conn: conn, + } +} + +func (c *AutoHttpsConn) readRequest() bool { + c.firstBuf = make([]byte, 2048) + n, err := c.Conn.Read(c.firstBuf) + c.firstBuf = c.firstBuf[:n] + if err != nil { + return false + } + reader := bytes.NewReader(c.firstBuf) + bufReader := bufio.NewReader(reader) + request, err := http.ReadRequest(bufReader) + if err != nil { + return false + } + resp := http.Response{ + Header: http.Header{}, + } + resp.StatusCode = http.StatusTemporaryRedirect + location := fmt.Sprintf("https://%v%v", request.Host, request.RequestURI) + resp.Header.Set("Location", location) + resp.Write(c.Conn) + c.Close() + c.firstBuf = nil + return true +} + +func (c *AutoHttpsConn) Read(buf []byte) (int, error) { + c.readRequestOnce.Do(func() { + c.readRequest() + }) + + if c.firstBuf != nil { + n := copy(buf, c.firstBuf[c.bufStart:]) + c.bufStart += n + if c.bufStart >= len(c.firstBuf) { + c.firstBuf = nil + } + return n, nil + } + + return c.Conn.Read(buf) +} |
