77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package request
|
|
|
|
import (
|
|
"git.xdrm.io/gws/http/upgrade/response"
|
|
"git.xdrm.io/gws/internal/http/reader"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// Parse builds an upgrade HTTP request
|
|
// from a reader (typically bufio.NewRead of the socket)
|
|
func Build(r io.Reader) (request *T, err error) {
|
|
|
|
req := new(T)
|
|
req.code = 500
|
|
|
|
|
|
/* (1) Parse request
|
|
---------------------------------------------------------*/
|
|
/* (1) Get chunk reader */
|
|
cr := reader.NewReader(r)
|
|
if err != nil {
|
|
return req, fmt.Errorf("Error while creating chunk reader: %s", err)
|
|
}
|
|
|
|
/* (2) Parse header line by line */
|
|
for {
|
|
|
|
line, err := cr.Read()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
|
|
if err != nil {
|
|
return req, fmt.Errorf("Cannot read from reader: %s", err)
|
|
}
|
|
|
|
err = req.parseHeader(line)
|
|
|
|
if err != nil {
|
|
return req, fmt.Errorf("Parsing error: %s\n", err);
|
|
}
|
|
|
|
}
|
|
|
|
/* (3) Check completion */
|
|
err = req.isComplete()
|
|
if err != nil {
|
|
req.code = response.BAD_REQUEST
|
|
return req, err
|
|
}
|
|
|
|
|
|
return req, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns a textual representation of the upgrade request
|
|
func (r T) String() string{
|
|
|
|
l1 := fmt.Sprintf("Upgrade Request\n - host: %s\n - port: %d\n - origin: %s\n", r.host, r.port, r.origin)
|
|
l2 := fmt.Sprintf(" - origin policy: %t\n - connection header: %t\n - upgrade header: %t\n - valid ws version: %t\n", r.validPolicy, r.hasConnection, r.hasUpgrade, r.hasVersion)
|
|
l3 := fmt.Sprintf(" - key: %s\n - protocols: %s\n", r.key, r.protocols)
|
|
l4 := fmt.Sprintf(" - current status: %d %s\n", r.code, r.code.Explicit())
|
|
|
|
|
|
return fmt.Sprintf("%s%s%s%s", l1, l2, l3, l4)
|
|
}
|
|
|
|
|
|
// StatusCode returns the status current
|
|
func (r T) StatusCode() response.StatusCode {
|
|
return r.code
|
|
}
|