webFramework

package
v2.0.0-...-51e8ac7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package webFramework provides the v2 web framework abstraction layer.

It extends the root module's github.com/hmmftg/requestCore/webFramework with renderer support, cookie access, and session/flash integration. Framework adapters (libGin, libFiber, libNetHttp) implement these interfaces for their respective HTTP frameworks.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BeforeCommitHook

type BeforeCommitHook func(*RequestContext) error

BeforeCommitHook is invoked by response methods before the adapter writes the response. Hooks may set cookies, persist session state, or record metrics. A hook must not write the response body itself.

Hook error handling depends on the hook's policy:

  • The session middleware's hook follows the configured SaveFailureMode (strict by default: the error is propagated so the response is not committed as a success; best-effort: the error is logged but the response is still committed).
  • Other hooks should be best-effort: log errors via webFramework.AddLog but return nil so the response can still be committed.

When a hook returns a non-nil error, the parser's SendResponse still proceeds with the write (the hook error is logged via addLogFailure). The session middleware in strict mode returns the error before the parser write path is reached, because RunBeforeCommitHooks is called before SendResponse in the commit path.

type CommitState

type CommitState struct {
	// contains filtered or unexported fields
}

CommitState tracks whether a response has been committed (status, headers, and body have been written) for a given request. All adapters must update this state when they write a response so that error dispatch, panic recovery, and session middleware can reliably avoid double-writes.

CommitState is safe for concurrent use, though a single request is typically processed by one goroutine.

func (*CommitState) Committed

func (c *CommitState) Committed() bool

Committed reports whether the response has been committed.

func (*CommitState) MarkCommitted

func (c *CommitState) MarkCommitted(status int)

MarkCommitted records that the response has been written with the given status code. Subsequent calls are ignored (the first commit wins).

func (*CommitState) Status

func (c *CommitState) Status() int

Status returns the committed status code, or 0 if not yet committed.

type CookieHelpers

type CookieHelpers interface {
	GetCookie(name string) string
	SetCookie(cookie *http.Cookie)
}

CookieHelpers is an optional interface that parsers may implement to expose cookie setting in a framework-neutral way. The base RequestParser interface already includes SetCookie; this is retained for documentation.

type ErrorContext

type ErrorContext struct {
	// Request is the v2 request context.
	Request *RequestContext

	// Error is the error to handle.
	Error error

	// Status is the resolved HTTP status code for this error.
	Status int
}

ErrorContext holds the context for an error handler invocation.

type ErrorHandler

type ErrorHandler func(ErrorContext) error

ErrorHandler processes an error and writes a response. It must call Request.Parser.SendResponse (or the legacy responder) to write the error response. If the handler fails to write a response, the registry will invoke the fallback handler exactly once.

type FakeParserV2

type FakeParserV2 struct {
	legacy.FakeParser

	// ResponseStatus captures the last status code passed to SendResponse.
	ResponseStatus int

	// ResponseContentType captures the last content type passed to SendResponse.
	ResponseContentType string

	// ResponseBody captures the last body bytes passed to SendResponse.
	ResponseBody []byte

	// ResponseWritten reports whether SendResponse was called.
	ResponseWritten bool

	// Cookies stores request cookies by name.
	Cookies map[string]string

	// SetCookies captures cookies set via SetCookie.
	SetCookies []*http.Cookie

	// HooksRan reports whether the hook runner was invoked.
	HooksRan bool
	// contains filtered or unexported fields
}

FakeParserV2 is a test implementation of the v2 RequestParser interface. It embeds the v1 FakeParser and adds raw response, cookie, and session/flash support for testing v2 handlers and middleware.

func NewFakeParserV2

func NewFakeParserV2() *FakeParserV2

NewFakeParserV2 creates a FakeParserV2 with initialized maps.

func (*FakeParserV2) Committed

func (f *FakeParserV2) Committed() bool

Committed reports whether SendResponse has been called.

func (*FakeParserV2) GetCookie

func (f *FakeParserV2) GetCookie(name string) string

GetCookie returns the value of the named request cookie.

func (*FakeParserV2) Reset

func (f *FakeParserV2) Reset()

Reset clears all captured response state for reuse between test cases.

func (*FakeParserV2) RunHookRunner

func (f *FakeParserV2) RunHookRunner()

RunHookRunner invokes the before-commit hook runner if set. This is used by test parsers that override SendResponse to ensure hooks still run before simulating write failures. Errors are ignored (best-effort).

func (*FakeParserV2) RunHookRunnerErr

func (f *FakeParserV2) RunHookRunnerErr() error

RunHookRunnerErr invokes the before-commit hook runner if set and returns any error. This is used by test parsers that need to propagate hook errors (e.g. strict-mode session save failures).

func (*FakeParserV2) SendResponse

func (f *FakeParserV2) SendResponse(status int, contentType string, body []byte) error

SendResponse captures the response parameters for test assertions. If a CommitState is bound and already committed, returns nil without writing. Before writing, the before-commit hook runner is invoked (if set) so that session cookies and other pre-write side effects are persisted even for direct parser writes.

func (*FakeParserV2) SetBeforeCommitHookRunner

func (f *FakeParserV2) SetBeforeCommitHookRunner(fn func() error)

SetBeforeCommitHookRunner binds a function that runs before-commit hooks before SendResponse writes the response.

func (*FakeParserV2) SetCommitState

func (f *FakeParserV2) SetCommitState(cs *CommitState)

SetCommitState binds the request's CommitState to this parser so that SendResponse can check and update the committed status.

func (*FakeParserV2) SetCookie

func (f *FakeParserV2) SetCookie(cookie *http.Cookie)

SetCookie captures the cookie for test assertions.

type FlashContext

type FlashContext interface {
	Add(key, value string)
	Get(key string) string
	Peek(key string) string
	Has(key string) bool
	Clear()
	GetAll() map[string]string
}

FlashContext is a minimal interface for flash message access from handlers. It avoids an import cycle with the session package while providing typed access.

The concrete *session.Flash type satisfies this interface implicitly.

type RequestContext

type RequestContext struct {
	// Context is the v2 request context (may carry cancellation, tracing).
	Context context.Context

	// LegacyContext is the framework-native context expected by
	// libContext.InitContext (e.g. *gin.Context, *fiber.Ctx, context.Context
	// with net/http request/response). Used by the legacy handler adapter.
	// It is typed as any because *fiber.Ctx does not implement
	// context.Context but is a valid input to libContext.InitContext.
	LegacyContext any

	// Parser is the v2 request parser.
	Parser RequestParser

	// Legacy is the v1 WebFramework, providing access to existing
	// query, persistence, response, logging, and tracing infrastructure.
	// Its Parser field is the same object as Parser above (type-asserted
	// to the legacy RequestParser interface).
	Legacy legacy.WebFramework

	// Session is the per-request session, loaded by session middleware.
	// May be nil if session middleware has not run. Typed as SessionContext
	// interface to avoid an import cycle with the session package while
	// providing typed access (no type assertions needed in handlers).
	// The concrete type is *session.Session, which satisfies SessionContext.
	Session SessionContext

	// Flash is the per-request flash, loaded by session middleware.
	// May be nil if session middleware has not run. Typed as FlashContext
	// interface to avoid an import cycle with the session package while
	// providing typed access. The concrete type is *session.Flash, which
	// satisfies FlashContext.
	Flash FlashContext
	// contains filtered or unexported fields
}

RequestContext holds the per-request state passed through the v2 handler and middleware pipeline.

func (*RequestContext) AddBeforeCommitHook

func (c *RequestContext) AddBeforeCommitHook(hook BeforeCommitHook)

AddBeforeCommitHook registers a hook to be invoked before the response is committed. Hooks fire in registration order. The hook slice is per-request and safe to mutate during request processing (not concurrently).

func (*RequestContext) CommitState

func (c *RequestContext) CommitState() *CommitState

CommitState returns the CommitState for this context, or nil if none has been associated. Adapters set this when building the RequestContext.

func (*RequestContext) Committed

func (c *RequestContext) Committed() bool

Committed reports whether the response for this context has been committed. Adapters update the embedded CommitState when they write a response.

func (*RequestContext) LegacyWebFramework

func (c *RequestContext) LegacyWebFramework() legacy.WebFramework

LegacyWebFramework returns the v1 WebFramework for use with existing query, persistence, response, and API-call helpers.

func (*RequestContext) MarkCommitted

func (c *RequestContext) MarkCommitted(status int)

MarkCommitted records the committed status. Adapters call this from their SendResponse implementation.

func (*RequestContext) RunBeforeCommitHooks

func (c *RequestContext) RunBeforeCommitHooks() error

RunBeforeCommitHooks invokes all registered before-commit hooks in order. This method is idempotent: the first call runs all hooks and subsequent calls return nil without re-running them. This ensures hooks run exactly once whether triggered by the parser's SendResponse or by response.Handler.commit. Errors are collected but do not abort the commit; the first error is returned for logging purposes.

func (*RequestContext) SetCommitState

func (c *RequestContext) SetCommitState(cs *CommitState)

SetCommitState associates a CommitState with this context and wires the before-commit hook runner on the parser so that SendResponse runs hooks before writing. Adapters call this during request setup after assigning c.Parser.

type RequestParser

type RequestParser interface {
	legacy.RequestParser

	// SendResponse writes a raw response with the given status code,
	// content type, and body bytes. The adapter handles framework-specific
	// transport mechanics (gin.Context.Writer, fiber.Ctx, http.ResponseWriter).
	//
	// If a CommitState has been bound via SetCommitState and the response
	// is already committed, this method returns nil without writing.
	// On successful write, the commit state is marked committed.
	SendResponse(status int, contentType string, body []byte) error

	// GetCookie returns the value of the named request cookie.
	// Returns "" if the cookie does not exist.
	GetCookie(name string) string

	// SetCookie sets an HTTP response cookie.
	SetCookie(cookie *http.Cookie)

	// SetCommitState binds the request's CommitState to this parser so
	// that SendResponse can check and update the committed status.
	// Adapters call this during request setup, after creating the parser
	// and before running handlers.
	SetCommitState(cs *CommitState)

	// SetBeforeCommitHookRunner binds a function that runs before-commit
	// hooks before the response is written. SendResponse implementations
	// must call this function (if non-nil) before writing the response,
	// so that direct writes (not going through response.Handler.commit)
	// also execute hooks such as session cookie persistence.
	//
	// The function is idempotent: repeated calls return nil after the
	// first invocation. Hook errors are logged inside the runner and do
	// not block the write.
	SetBeforeCommitHookRunner(fn func() error)
}

RequestParser extends the v1 RequestParser with raw response writing, cookie access, and session/flash support.

Renderers produce encoded bytes; the parser's SendResponse method writes them to the framework-specific transport. This avoids leaking net/http types (like http.ResponseWriter) into Fiber/fasthttp adapters.

All SendResponse implementations must check and update the bound CommitState so that error dispatch, panic recovery, and session middleware can reliably avoid double-writes across v2 and legacy response paths.

type SessionContext

type SessionContext interface {
	Get(key string) any
	GetString(key string) string
	Set(key string, value any)
	Delete(key string)
	Clear()
	IsDirty() bool
	ID() string
}

SessionContext is a minimal interface for session access from handlers. It avoids an import cycle with the session package while providing typed access — no `any` type assertions needed in handlers.

The concrete *session.Session type satisfies this interface implicitly.

type StatusResolver

type StatusResolver func(error) int

StatusResolver determines the HTTP status code for an error. Implementations should use errors.As to inspect wrapped errors and extract status from libError.Error, response.ErrorState, or any type implementing interface{ HTTPStatus() int }.

type WebFrameworkV2

type WebFrameworkV2 struct {
	RequestContext
}

WebFrameworkV2 is a convenience wrapper that bundles a RequestContext with its parser and legacy framework. It is used by response handlers and error handlers that need both v1 and v2 access.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL