💾 Archived View for source.community › ckaznocha › gemini › raw › main › geminitest › recorder.go captured on 2023-07-10 at 13:42:23.

View Raw

More Information

⬅️ Previous capture (2021-12-17)

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

package geminitest

import (
	"bytes"
	"context"
	"io"

	"source.community/ckaznocha/gemini"
)

// ResponseRecorder may be used in test to capture the output of a Handler.
type ResponseRecorder struct {
	Body *bytes.Buffer
	Meta string
	Code gemini.StatusCode
}

var _ gemini.ResponseWriter = (*ResponseRecorder)(nil)

// NewResponseRecorder returns a response recorder ready to use.
func NewResponseRecorder() *ResponseRecorder {
	return &ResponseRecorder{
		Body: bytes.NewBuffer(nil),
	}
}

// Failure implements the Failure method of the ResponseWriter interface.
func (r *ResponseRecorder) Failure(ctx context.Context, code gemini.StatusCode, msg string) {
	category := code.ToCategory()
	if category < gemini.StatusCategoryTemporaryFailure || category > gemini.StatusCategoryPermanentFailure {
		code = gemini.StatusPermanentFailure
	}

	r.Code = code
	r.Meta = msg
}

// Input implements the Input method of the ResponseWriter interface.
func (r *ResponseRecorder) Input(ctx context.Context, prompt string, isSensitive bool) {
	code := gemini.StatusInput
	if isSensitive {
		code = gemini.StatusSensitiveInput
	}

	r.Code = code
	r.Meta = prompt
}

// Redirect implements the Redirect method of the ResponseWriter interface.
func (r *ResponseRecorder) Redirect(ctx context.Context, redirectURL string, isPermanant bool) {
	code := gemini.StatusTemporaryRedirect
	if isPermanant {
		code = gemini.StatusPermanentRedirect
	}

	r.Code = code
	r.Meta = redirectURL
}

// Success implements the Success method of the ResponseWriter interface.
func (r *ResponseRecorder) Success(ctx context.Context, mimeType string) io.Writer {
	r.Code = gemini.StatusSuccess
	r.Meta = mimeType

	return r.Body
}