client-hello-mirror/request.go

64 lines
1.2 KiB
Go

// SPDX-FileCopyrightText: 2022-2023 nervuri <https://nervuri.net/contact>
//
// SPDX-License-Identifier: BSD-3-Clause
package main
import (
"errors"
"net/url"
"strings"
)
type request struct {
Protocol int
HTTPMethod int
Path string
Query string
}
// Supported protocols
const (
httpProtocol = 1
geminiProtocol = 2
)
// Supported HTTP methods
const (
getMethod = 1
headMethod = 2
)
var ErrNotSupported = errors.New("Unsupported protocol or HTTP method")
// Get request information from the first line of the request.
func getRequestInfo(firstLine string) (req request, err error) {
var urlStr string // the string to be passed to url.Parse()
if strings.HasPrefix(firstLine, "gemini://") {
req.Protocol = geminiProtocol
urlStr = firstLine
} else if strings.HasPrefix(firstLine, "GET ") {
req.HTTPMethod = getMethod
} else if strings.HasPrefix(firstLine, "HEAD ") {
req.HTTPMethod = headMethod
} else {
err = ErrNotSupported
return
}
if req.HTTPMethod != 0 {
req.Protocol = httpProtocol
urlStr = strings.Split(firstLine, " ")[1]
}
var u *url.URL
u, err = url.Parse(urlStr)
if err != nil {
return
}
req.Path = u.Path
req.Query = u.RawQuery
if req.Path == "" {
req.Path = "/"
}
return
}