💾 Archived View for source.community › ckaznocha › gemini › raw › main › request.go captured on 2023-04-26 at 13:29:33.

View Raw

More Information

⬅️ Previous capture (2021-12-17)

➡️ Next capture (2023-07-10)

-=-=-=-=-=-=-

package gemini

import (
	"bufio"
	"crypto/x509/pkix"
	"fmt"
	"net/textproto"
)

const maxRequestLength = 1024

// Request is a Gemini request.
type Request struct {
	Subject    *pkix.Name
	URI        *URI
	RemoteAddr string
}

// ReadRequest reads and parses a Gemini request from buffer. It returns an
// error if the request could not be read or was  malformed.
func ReadRequest(b *bufio.Reader) (*Request, error) {
	u := []byte{}
	cr := false

	for {
		b, err := b.ReadByte()
		if err != nil {
			return nil, fmt.Errorf("%w: %s", ErrRequestRead, err)
		}

		if b == '\r' {
			cr = true

			continue
		}

		if cr && b == '\n' {
			break
		}

		cr = false

		u = append(u, b)
		if len(u) > maxRequestLength {
			return nil, ErrMaxRequestLengthExceeded
		}
	}

	uri, err := ParseRequestURI(string(textproto.TrimBytes(u)))
	if err != nil {
		return nil, err
	}

	return &Request{URI: uri}, nil
}