httputil

package
v0.3.28 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package httputil provides shared HTTP helper utilities used across multiple HTTP-facing packages (server, proxy, etc.).

Index

Constants

View Source
const GitHubUserAgent = "awmg/1.0"

GitHubUserAgent is the User-Agent header value sent on all GitHub API requests.

View Source
const MinTLSVersion = tls.VersionTLS12

MinTLSVersion is the minimum TLS version enforced across all gateway listeners and clients. Centralizing this constant ensures a single point of change if the policy is tightened (e.g., to tls.VersionTLS13).

Variables

This section is empty.

Functions

func ApplyGitHubAPIHeaders added in v0.3.1

func ApplyGitHubAPIHeaders(req *http.Request, authHeader string)

ApplyGitHubAPIHeaders sets the standard GitHub API request headers on req. authHeader should be the full Authorization header value (e.g. "token xyz" or "Bearer xyz"). When authHeader is empty no Authorization header is set, which is appropriate when the caller has already decided that no auth is available.

func ComputeRetryAfter added in v0.3.26

func ComputeRetryAfter(resetAt time.Time) int

ComputeRetryAfter returns the number of seconds a client should wait before retrying after a rate-limit response. It accepts the parsed reset time from ParseRateLimitResetHeader. When resetAt is in the future the delay is clamped to [1, 3600] seconds. When resetAt is zero or already in the past a default of 60 seconds is returned.

func DoGitHubGET added in v0.3.17

func DoGitHubGET(ctx context.Context, apiBaseURL, path, authHeader string) (*http.Response, error)

DoGitHubGET sends an authenticated GET request to the GitHub API and returns the response. apiBaseURL is the API root (e.g. "https://api.github.com"), path is the request path (e.g. "/repos/owner/repo"), and authHeader is the full Authorization header value (e.g. "token xyz"). The caller is responsible for closing the response body. Request duration is bounded by whichever happens first: ctx cancellation/deadline or the helper client timeout.

func FetchCollaboratorPermission added in v0.3.19

func FetchCollaboratorPermission(
	ctx context.Context,
	owner, repo, username string,
	fetch func(ctx context.Context, apiPath string) (*http.Response, error),
	logPrintf func(format string, args ...interface{}),
) (interface{}, error)

FetchCollaboratorPermission executes a get_collaborator_permission REST call using the provided fetch function and returns the wrapped MCP text response.

The fetch callback should perform the authenticated HTTP request for the given API path and return the upstream response.

func IsTransientHTTPError added in v0.2.25

func IsTransientHTTPError(statusCode int) bool

IsTransientHTTPError returns true for status codes that indicate a temporary server-side condition (rate-limiting or transient failure) worth retrying.

func LogAndWrapCollaboratorPermission added in v0.3.19

func LogAndWrapCollaboratorPermission(
	body []byte,
	owner, repo, username string,
	statusCode int,
	logPrintf func(format string, args ...interface{}),
) interface{}

LogAndWrapCollaboratorPermission parses the raw GitHub API response body for a get_collaborator_permission request, logs the resolved permission level for observability, and returns the body wrapped in MCP text-response format.

This helper is shared between the server and proxy packages to eliminate duplicated parse/log/wrap logic. Callers pass their own debug logger's Printf method so that log lines appear under the correct namespace.

func NewClientTLSConfig added in v0.3.28

func NewClientTLSConfig() *tls.Config

NewClientTLSConfig returns a *tls.Config suitable for outbound HTTP clients, enforcing the gateway-wide minimum TLS version.

func NewServerTLSConfig added in v0.3.28

func NewServerTLSConfig(cert tls.Certificate) *tls.Config

NewServerTLSConfig returns a *tls.Config for TLS server listeners carrying the provided certificate and the gateway-wide minimum TLS version.

func ParseCollaboratorPermissionArgs added in v0.3.19

func ParseCollaboratorPermissionArgs(argsMap map[string]interface{}) (owner, repo, username string, err error)

ParseCollaboratorPermissionArgs extracts and validates the owner, repo, and username fields from an args map for a get_collaborator_permission call. It returns the (possibly partial) values even on error so that callers can include them in diagnostic log messages.

func ParseRateLimitResetHeader added in v0.2.20

func ParseRateLimitResetHeader(value string) time.Time

ParseRateLimitResetHeader parses the Unix-timestamp value of the X-RateLimit-Reset HTTP header into a time.Time. Returns zero time when the header value is absent or malformed.

See also: parseRateLimitResetFromText in server/rate_limit.go, which parses the same timing information from MCP tool result text bodies instead of HTTP headers.

func WriteErrorResponse added in v0.3.2

func WriteErrorResponse(w http.ResponseWriter, statusCode int, code, message string)

WriteErrorResponse writes a JSON error response with a consistent {"error": code, "message": message} shape. Both the server and proxy packages should use this helper so that API consumers always receive the same error shape.

func WriteJSONResponse

func WriteJSONResponse(w http.ResponseWriter, statusCode int, body interface{})

WriteJSONResponse sets the Content-Type header, writes the status code, and encodes body as JSON. It centralises the three-line pattern used across HTTP handlers.

func WriteReflectResponse added in v0.3.25

func WriteReflectResponse(w http.ResponseWriter, difcComponents difc.DIFCComponents)

WriteReflectResponse writes the DIFC label snapshot JSON response for /reflect endpoints. Both the server and the proxy expose /reflect; sharing this helper ensures the output format evolves consistently as difc.BuildReflectResponse changes.

func WriteSimpleHealthResponse added in v0.3.25

func WriteSimpleHealthResponse(w http.ResponseWriter)

WriteSimpleHealthResponse writes a minimal {"status":"ok"} JSON health response. This is the standard health response shape for endpoints that do not have access to detailed server status (e.g. the proxy), keeping them consistent with each other.

Types

type BaseResponseWriter added in v0.3.14

type BaseResponseWriter struct {
	http.ResponseWriter
	// StatusCode holds the captured HTTP status code. It is set by WriteHeader
	// and, if still zero when Write is first called, defaults to http.StatusOK.
	// Only the first call to WriteHeader or Write sets StatusCode, matching
	// net/http semantics where only the first status sent is effective.
	StatusCode int
	// contains filtered or unexported fields
}

BaseResponseWriter wraps http.ResponseWriter and captures the HTTP response status code. It implements Write (with implicit-200 capture), WriteHeader, and Unwrap so that http.ResponseController callers can access optional interfaces (e.g. http.Flusher, http.Hijacker) on the underlying writer.

Embed BaseResponseWriter in package-specific types to avoid duplicating this status-capture boilerplate.

func (*BaseResponseWriter) Unwrap added in v0.3.14

Unwrap returns the underlying http.ResponseWriter so that callers using http.ResponseController can discover optional interfaces such as http.Flusher or http.Hijacker on the real writer.

func (*BaseResponseWriter) Write added in v0.3.14

func (w *BaseResponseWriter) Write(b []byte) (int, error)

Write captures an implicit 200 status on first call when no prior WriteHeader was issued, then delegates to the underlying writer.

func (*BaseResponseWriter) WriteHeader added in v0.3.14

func (w *BaseResponseWriter) WriteHeader(code int)

WriteHeader captures the status code on first call and forwards it to the underlying writer. Subsequent calls are forwarded but do not update StatusCode, matching net/http semantics where only the first WriteHeader is effective.

Jump to

Keyboard shortcuts

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