ws/http/upgrade/request/private.go

94 lines
1.9 KiB
Go
Raw Normal View History

package request
import (
"strings"
"strconv"
"fmt"
"git.xdrm.io/gws/internal/http/upgrade/request/parser/header"
)
// parseHeader parses any http request line
// (header and request-line)
func (r *T) parseHeader(b []byte) error {
/* (1) First line -> GET {uri} HTTP/{version}
---------------------------------------------------------*/
if !r.first {
err := r.request.Parse(b)
if err != nil {
return fmt.Errorf("Error while parsing first line: %s", err)
}
r.first = true
return nil
}
/* (2) Other lines -> Header-Name: Header-Value
---------------------------------------------------------*/
/* (1) Try to parse header */
head, err := header.Parse(b)
if err != nil {
return fmt.Errorf("Error parsing header: %s", err)
}
/* (2) Manage header */
switch head.Name {
case header.HOST: fmt.Printf("[host] ")
err = r.extractHostPort(head.Values[0])
case header.UPGRADE: fmt.Printf("[upgrade] ")
case header.CONNECTION: fmt.Printf("[connection] ")
case header.WSKEY: fmt.Printf("[sec-websocket-key] ")
case header.ORIGIN: fmt.Printf("[origin] ")
case header.WSPROTOCOL: fmt.Printf("[sec-websocket-protocol] ")
case header.WSVERSION: fmt.Printf("[sec-websocket-version] ")
default:
return nil
}
if err != nil { return err }
for i, v := range head.Values {
if i == 0 {
fmt.Printf("[ '%s'", v)
} else {
fmt.Printf(", '%s'", v)
}
}
fmt.Printf(" ]\n");
return nil
}
// checkHost checks and extracts the Host header
func (r *T) extractHostPort(b []byte) error {
split := strings.Split(string(b), ":")
r.host = split[0]
// no port
if len(split) < 2 {
return nil
}
// extract port
readPort, err := strconv.ParseUint(split[1], 10, 16)
if err != nil {
return fmt.Errorf("Cannot read port number '%s'", split[1])
}
r.port = uint16(readPort)
return nil
}