Help us shape the future of Go! Take the 2026 Go Developer Survey

request

package
v1.42.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MTLSClientCertFileFlag = "mtls-client-cert-file"
	MTLSClientCertFileEnv  = "OPENAI_MTLS_CLIENT_CERT_FILE"
	MTLSClientKeyFileFlag  = "mtls-client-key-file"
	MTLSClientKeyFileEnv   = "OPENAI_MTLS_CLIENT_KEY_FILE"
	MTLSHTTPClientMetadata = "mtls-http-client"
)
View Source
const BaseURLHTTPSRequired = " must use HTTPS, except for localhost or a loopback IP address"
View Source
const BaseURLHostRequired = " must be an absolute HTTP(S) URL with a valid host"
View Source
const UntrustedStdinEnv = "OPENAI_UNTRUSTED_STDIN"

UntrustedStdinEnv selects literal interpretation of piped request values.

Variables

This section is empty.

Functions

func ApplyDataAliases

func ApplyDataAliases(cmd *cli.Command, bodyMap map[string]any)

ApplyDataAliases rewrites keys in a body map based on flag `DataAliases` metadata. For top-level flags, `{alias: value}` becomes `{canonical: value}`. For inner flags (those registered under an outer flag via WithInnerFlags), the alias translation is also applied to the nested map under the outer flag's body path, so values like `--parent '{"alias": val}'` resolve to the canonical inner field name.

func CloseFileUploads

func CloseFileUploads(value any) error

CloseFileUploads closes every source owned by a FileUpload, including values nested inside maps and arrays. Other io.ReadClosers (notably stdin wrappers) are intentionally left alone because this code does not own them.

func ConfigureMTLS

func ConfigureMTLS(ctx context.Context, cmd *cli.Command) (context.Context, error)

ConfigureMTLS stores the root command's configured mTLS client for request consumers.

func ConfigureRootFlags

func ConfigureRootFlags(root *cli.Command)

ConfigureRootFlags makes only root request configuration inheritable. Endpoint request flags retain their local scope, including a body --project.

func DefaultOptions

func DefaultOptions(cmd *cli.Command, version string, middlewares ...option.Middleware) []option.RequestOption

DefaultOptions builds shared client configuration around caller-supplied middleware. Middleware order stays between CLI metadata and explicit request overrides.

func EmbedFiles

func EmbedFiles(obj any, embedStyle FileEmbedStyle, stdin *OnceStdinReader) (any, error)

EmbedFiles expands trusted file references and preserves borrowed stdin ownership.

func EmbedRequestFiles

func EmbedRequestFiles(command *cli.Command, value any, area string, style FileEmbedStyle, stdin *OnceStdinReader) (any, error)

EmbedRequestFiles expands references with declared request-option provenance.

func EncodeOptions

func EncodeOptions(
	cmd *cli.Command,
	contents requestflag.RequestContents,
	nestedFormat apiquery.NestedQueryFormat,
	arrayFormat apiquery.ArrayQueryFormat,
	bodyType BodyContentType,
	hooks EncodingHooks,
) (options []option.RequestOption, err error)

EncodeOptions serializes already-expanded query, header, and body values. Explicit literal headers are appended by the caller after these options. On success, a multipart body owns its uploads. Until then, the caller retains responsibility for closing uploads, including failures from feature hooks.

func FlagOptions

func FlagOptions(
	cmd *cli.Command,
	nestedFormat apiquery.NestedQueryFormat,
	arrayFormat apiquery.ArrayQueryFormat,
	bodyType BodyContentType,
	ignoreStdin bool,
	stdin io.Reader,
	hooks PreparationHooks,
) (options []option.RequestOption, err error)

FlagOptions prepares request options from flags and borrowed stdin. Stdin classification retains the process stdin probe even when a workflow supplies a cancellation-aware reader. ignoreStdin reserves stdin for a binary body. Feature callbacks run at the same preflight, credential, expansion, and encoding points as ordinary request preparation, before upload ownership transfers.

func Headers

func Headers(cmd *cli.Command) (http.Header, error)

Headers parses literal header flags without echoing their values in errors.

func IsStdinPath

func IsStdinPath(s string) bool

IsStdinPath recognizes the supported aliases for standard input.

func IsUTF8TextFile

func IsUTF8TextFile(content []byte) bool

IsUTF8TextFile reports whether content has a supported text MIME type and valid UTF-8.

func MTLSClientFlags

func MTLSClientFlags() []cli.Flag

MTLSClientFlags returns certificate and key flags with their existing source rules.

func MultipartRequestOptions

func MultipartRequestOptions(
	bodyMap map[string]any,
	encodingFormat apiform.FormFormat,
	observeBody ...func(io.Closer),
) ([]option.RequestOption, error)

MultipartRequestOptions keeps scalar-only forms buffered and replayable. Forms containing an upload stream exactly once: the SDK retry loop is disabled because the CLI cannot promise that a reader will produce identical bytes a second time. Regular files retain an exact Content-Length; unknown sources use chunked transfer encoding.

func NewMTLSHTTPClient

func NewMTLSHTTPClient(certFile, keyFile, baseURL string) (*http.Client, error)

NewMTLSHTTPClient constructs an endpoint-bound mTLS client using default transport settings.

func NewRequestHeaderFlag

func NewRequestHeaderFlag() cli.Flag

NewRequestHeaderFlag returns the repeatable, global flag for literal HTTP headers.

func NextCommandOptions

func NextCommandOptions(root *cli.Command) (args []string, omit bool)

NextCommandOptions reproduces request selection without copying credentials into terminal output.

func ProtectStdinValue

func ProtectStdinValue(value any) any

ProtectStdinValue marks ordinary string leaves while preserving other values.

func ReadMultipartScalar added in v1.39.1

func ReadMultipartScalar(ctx context.Context, name string, value any) (any, any, error)

ReadMultipartScalar inspects scalar @file references that arrive as upload readers after shared trusted-input expansion. Inspect their contents once and replay the exact original bytes, retaining multipart filenames/content types. Source image and mask readers never enter this path and stay streamed. There is no new file-size limit.

func ReadPipedInput

func ReadPipedInput(cmd *cli.Command, stdin io.Reader, contents *requestflag.RequestContents, stdinSecurity *StdinSecurity, acceptBody bool) (bool, error)

ReadPipedInput reads borrowed request input and merges it with explicit flags. The caller decides whether stdin is eligible for whole-request input. The result reports whether nonempty input consumed stdin, including input that failed to parse. Bodyless requests still apply path, query, and header values without merging a body.

func ResolveStreamingInput

func ResolveStreamingInput(command *cli.Command, body []byte) error

ResolveStreamingInput aligns generated dispatch with the final JSON without rewriting request bytes.

func ResolveStreamingValue

func ResolveStreamingValue(command *cli.Command, streaming bool) error

ResolveStreamingValue applies a resolved Boolean without overriding explicit stream flags.

func StdinConsumers

func StdinConsumers(contents requestflag.RequestContents, reserved bool) (int, error)

StdinConsumers counts the values that file embedding consumes, without reading them. Count effective values so a replaced scalar flag does not claim stdin twice.

func ValidateBaseURL

func ValidateBaseURL(value, source string) error

ValidateBaseURL permits cleartext HTTP only for explicit local development endpoints. Use the same URL parser as the SDK, and never resolve DNS names to grant an exception.

func WrapFileInputValues

func WrapFileInputValues(cmd *cli.Command, contents *requestflag.RequestContents, stdinSecurity *StdinSecurity) error

WrapFileInputValues replaces string values for FileInput flags (type: string, format: binary) with FilePathValue sentinel values. embedFilesValue recognizes FilePathValue and reads the file contents directly, so the user doesn't need to type the "@" prefix. Untrusted piped file paths are rejected before any file can be opened.

Types

type BodyContentType

type BodyContentType int
const (
	EmptyBody BodyContentType = iota
	MultipartFormEncoded
	ApplicationJSON
	ApplicationOctetStream
)

type EncodingHooks

type EncodingHooks struct {
	PrepareMultipart func(map[string]any) error
	ObserveMultipart func(io.Closer)
	ValidateJSON     func([]byte) error
	ObserveJSON      []func([]byte)
}

EncodingHooks retains feature validation and observation at their existing serialization points without making shared request code depend on features.

type FileEmbedStyle

type FileEmbedStyle int

FileEmbedStyle selects text substitution or streaming upload expansion.

const (
	// EmbedText reads referenced files fully into memory and substitutes the file's contents back into the
	// value as a string. Binary files are base64-encoded. Used for JSON request bodies and for headers and
	// query parameters, where the file contents need to be serialized inline.
	EmbedText FileEmbedStyle = iota

	// EmbedIOReader replaces file references with an io.Reader that streams the file's contents. Used for
	// `multipart/form-data` and `application/octet-stream` request bodies, where files are uploaded as binary
	// parts rather than embedded into a text value.
	EmbedIOReader
)

type FileInputSource

type FileInputSource struct {
	Option string
	// contains filtered or unexported fields
}

FileInputSource follows declared request fields through file expansion. It never retains argument values or infers an option from a file path.

func (FileInputSource) Failure

func (s FileInputSource) Failure(operation string, err error) error

Failure preserves the original cause and its declared option, without wrapping a clean EOF.

func (FileInputSource) OpenUpload

func (s FileInputSource) OpenUpload(path string) (FileUpload, error)

OpenUpload opens an owned upload with option metadata on open, read, and close failures.

func (FileInputSource) ReadFile

func (s FileInputSource) ReadFile(path string) ([]byte, error)

ReadFile reads a local source while retaining option metadata on failures.

type FilePathValue

type FilePathValue string

FilePathValue is a string wrapper that marks a value as a file path whose contents should be read and embedded in the request. A FilePathValue is always interpreted as a file path without needing the "@" prefix.

type FileUpload

type FileUpload struct {
	io.Reader // apiform checks for reader and reads its contents during encode
	FileName  string
	MediaType string
	Size      int64
	KnownSize bool
}

FileUpload wraps an io.Reader with filename and content-type metadata for use as a multipart form part. The apiform encoder detects the Filename and ContentType methods and uses them to populate the Content-Disposition filename and the Content-Type header on the part. The upload owns its Reader; KnownSize distinguishes an exact byte count from an unknown-length source.

func OpenFileUpload

func OpenFileUpload(path string) (FileUpload, error)

OpenFileUpload opens path once. Ordinary files retain their exact stat size so the request can stream with Content-Length. Virtual and unknown-length files remain single-shot streams with chunked transfer encoding.

func (FileUpload) Close

func (f FileUpload) Close() error

func (FileUpload) ContentType

func (f FileUpload) ContentType() string

func (FileUpload) Filename

func (f FileUpload) Filename() string

type HeaderFlag

type HeaderFlag struct {
	requestflag.Flag[[]string]
}

HeaderFlag is the root-owned repeatable flag for literal request headers.

func (*HeaderFlag) IsLocal

func (*HeaderFlag) IsLocal() bool

type InputFileError

type InputFileError struct {
	Option, Operation string
	// contains filtered or unexported fields
}

InputFileError retains the actual failure and only a declared option name. Its cause remains available through errors.Is, errors.As, and joined errors.

func (*InputFileError) Error

func (e *InputFileError) Error() string

func (*InputFileError) Unwrap

func (e *InputFileError) Unwrap() error

type InputFileReader

type InputFileReader struct {
	io.Reader
	Source FileInputSource
}

InputFileReader annotates read and close failures with a declared option.

func (*InputFileReader) Close

func (r *InputFileReader) Close() error

func (*InputFileReader) Read

func (r *InputFileReader) Read(p []byte) (int, error)

type MTLSClientFlag

type MTLSClientFlag struct {
	cli.StringFlag
	// contains filtered or unexported fields
}

MTLSClientFlag permits one explicit value, independently of an environment default. The embedded PostParse applies sources without consuming the explicit allowance.

func (*MTLSClientFlag) CLIStringFlag

func (f *MTLSClientFlag) CLIStringFlag() *cli.StringFlag

CLIStringFlag exposes metadata without changing parsing or source ownership.

func (*MTLSClientFlag) PreParse

func (f *MTLSClientFlag) PreParse() error

func (*MTLSClientFlag) Set

func (f *MTLSClientFlag) Set(name, value string) error

type MultipartScalarError added in v1.39.1

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

MultipartScalarError retains a scalar read failure behind its declared flag name.

func (*MultipartScalarError) Error added in v1.39.1

func (e *MultipartScalarError) Error() string

func (*MultipartScalarError) Unwrap added in v1.39.1

func (e *MultipartScalarError) Unwrap() error

type OnceStdinReader

type OnceStdinReader struct {
	Reader        io.Reader
	FailureReason string
}

OnceStdinReader wraps an io.Reader that can only be consumed once, used to ensure stdin is read by at most one parameter (or only for a body root parameter or only for YAML parameter input). If FailureReason is set, stdin is unavailable and Take() returns an error explaining why.

func (*OnceStdinReader) ReadAll

func (o *OnceStdinReader) ReadAll() ([]byte, error)

ReadAll claims stdin and reads its contents without closing the borrowed reader.

func (*OnceStdinReader) Take

func (o *OnceStdinReader) Take() (io.Reader, error)

Take claims the single stdin consumer without closing the borrowed reader.

type PreparationHooks

type PreparationHooks struct {
	DebugCapture        debugmiddleware.CaptureOptions
	PreflightMultipart  func(map[string]any) error
	ValidateCredentials func() error
	// ValidateResolvedInputs runs after file expansion, while preparation owns opened uploads.
	ValidateResolvedInputs func(requestflag.RequestContents) error
	// ResolvedJSONOptions inspects finalized inputs before JSON observers run.
	// Literal headers retain precedence over every returned request option.
	ResolvedJSONOptions func(map[string]any, http.Header, []byte) []option.RequestOption
	// EmbedMultipart owns partial-result cleanup on failure. On success, shared
	// preparation takes responsibility for the returned uploads until encoding.
	EmbedMultipart func(map[string]any, *OnceStdinReader) (map[string]any, error)
	Encoding       EncodingHooks
}

PreparationHooks keeps feature validation and multipart specialization with assembly while shared request code owns input precedence and upload cleanup.

type RootRequestFlag

type RootRequestFlag struct {
	*requestflag.Flag[string]
}

RootRequestFlag preserves request metadata while sharing root options with subcommands.

func (*RootRequestFlag) IsLocal

func (*RootRequestFlag) IsLocal() bool

func (*RootRequestFlag) RequestFlag

func (f *RootRequestFlag) RequestFlag() *requestflag.Flag[string]

RequestFlag exposes the existing metadata for help decoration and redaction.

type StdinSecurity

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

StdinSecurity tracks the origin of piped values for one request preparation.

func NewStdinSecurity

func NewStdinSecurity() (*StdinSecurity, error)

NewStdinSecurity reads the untrusted-stdin setting for this request.

func (*StdinSecurity) Enabled

func (s *StdinSecurity) Enabled() bool

Enabled reports whether piped values require literal interpretation.

func (*StdinSecurity) ProtectFlagValues

func (s *StdinSecurity) ProtectFlagValues(contents *requestflag.RequestContents)

ProtectFlagValues preserves recorded values as literals during file expansion.

func (*StdinSecurity) RecordBodyFlags

func (s *StdinSecurity) RecordBodyFlags(cmd *cli.Command, data map[string]any)

RecordBodyFlags records unset body flags represented in piped data.

func (*StdinSecurity) RecordFlag

func (s *StdinSecurity) RecordFlag(flag cli.Flag)

RecordFlag records a flag populated from piped input.

type UntrustedStdinValue

type UntrustedStdinValue string

UntrustedStdinValue preserves a string's origin until the shared file expansion boundary, where its contents are always interpreted literally.

Jump to

Keyboard shortcuts

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