81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
|
|
package proxy
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"net"
|
||
|
|
"strconv"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
type UHttpRequest struct {
|
||
|
|
Conn net.Conn
|
||
|
|
io *UReader
|
||
|
|
IsLoadHeader bool
|
||
|
|
DataSize int
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewHttpRequest(conn net.Conn) *UHttpRequest {
|
||
|
|
return &UHttpRequest{
|
||
|
|
Conn: conn,
|
||
|
|
io: NewReader(conn),
|
||
|
|
IsLoadHeader: false,
|
||
|
|
DataSize: 0,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) ReadLine() ([]byte, error) {
|
||
|
|
line, err := req.io.ReadLine()
|
||
|
|
if err != nil {
|
||
|
|
return line, err
|
||
|
|
}
|
||
|
|
if !req.IsLoadHeader && bytes.Equal(line, []byte("\r\n")) {
|
||
|
|
req.IsLoadHeader = true
|
||
|
|
}
|
||
|
|
if !req.IsLoadHeader {
|
||
|
|
k, v, ok := bytes.Cut(line, []byte(":"))
|
||
|
|
if !ok {
|
||
|
|
return line, err
|
||
|
|
}
|
||
|
|
if bytes.Equal(k, []byte("Content-Length")) {
|
||
|
|
nv := strings.Trim(string(v), " \r\n")
|
||
|
|
n, err := strconv.ParseUint(nv, 10, 63)
|
||
|
|
if err != nil {
|
||
|
|
return line, err
|
||
|
|
}
|
||
|
|
req.DataSize = int(n)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return line, err
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) Read(data []byte, s int, e int) (int, error) {
|
||
|
|
return req.io.Read(data, s, e)
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) Write(data []byte) (int, error) {
|
||
|
|
return req.Conn.Write(data)
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) WriteError(err error) error {
|
||
|
|
return req.WriteHttp([]byte("HTTP/1.1 200 OK\r\n"), []byte(err.Error()))
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) WriteHttp(header []byte, data []byte) error {
|
||
|
|
_, err := req.Write(header)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
var bufBody bytes.Buffer
|
||
|
|
bufBody.WriteString("{\n \"error\" : \"")
|
||
|
|
bufBody.WriteString(string(data))
|
||
|
|
bufBody.WriteString("\"\n}")
|
||
|
|
var bufWrap bytes.Buffer
|
||
|
|
bufWrap.WriteString("Content-Length:")
|
||
|
|
bufWrap.WriteString(strconv.Itoa(bufBody.Len()))
|
||
|
|
bufWrap.WriteString("\r\n\r\n")
|
||
|
|
_, err = req.Write(bufWrap.Bytes())
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
_, err = req.Write(bufBody.Bytes())
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
func (req *UHttpRequest) Clear() {
|
||
|
|
req.io.Clear()
|
||
|
|
}
|