httpfile

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpfile parses the common subset of the `.http` request file format used by VS Code REST Client, JetBrains HTTP Client, kulala.nvim and httpyac, plus apic's own `# @capture` / `# @assert` comment directives.

Index

Constants

View Source
const (
	HTTP1 = "HTTP/1.1"
	HTTP2 = "HTTP/2"
)

The HTTP versions a request line can ask for.

View Source
const DefaultRetryInterval = time.Second

DefaultRetryInterval is the wait between attempts when a retry policy gives none.

View Source
const GraphQLHeader = "X-REQUEST-TYPE"

GraphQLHeader is the REST Client header that marks a GraphQL request. It is never sent on the wire.

Variables

View Source
var Codes = map[string]string{
	"orphan-directives":   "directives that are not followed by a request line",
	"bad-name":            "`# @name` without a value",
	"bad-capture":         "`# @capture` that is not `name = selector`",
	"bad-assert":          "`# @assert` that is not `selector op value`",
	"bad-header":          "a line in the header section that is not `Name: value`",
	"unknown-directive":   "a `# @directive` apic does not know (ignored)",
	"editor-script":       "an editor-only script or redirect block (skipped, not sent)",
	"duplicate-name":      "a request name used more than once in the project",
	"bad-auth":            "an `# @auth` spec that does not parse",
	"exec-disabled":       "`# @auth exec` without auth.allowExec in apic.yaml",
	"bad-config-auth":     "auth.default in apic.yaml does not parse",
	"bad-step":            "a `# @step` phrase that does not parse",
	"ambiguous-step":      "a `# @step` phrase that matches the same text as another step",
	"bad-ref":             "a `# @ref` or `# @forceRef` whose target is not one request in the project",
	"ref-cycle":           "a `# @ref` chain that leads back to the request it started from",
	"bad-retry":           "a `# @retry` (or retry in apic.yaml) that is not `<attempts> [interval]`",
	"bad-sleep":           "a `# @sleep` whose value is not a duration such as 500ms or 2s",
	"bad-http-version":    "a request line whose HTTP version is not HTTP/1.1 or HTTP/2",
	"bad-auth-config":     "a JetBrains `Security.Auth` configuration in an env file that apic cannot use (not OAuth2, the Implicit grant, a missing Token URL or Client ID)",
	"unknown-auth-key":    "a field of a `Security.Auth` configuration that apic does not act on",
	"unknown-selector":    "a selector that is not status, statusText, duration, header.*, cookie.*, body or body.$*, or a body path apic cannot read",
	"missing-body-file":   "a `< file` body, or a `< file` part of a multipart body, whose file does not exist",
	"bad-multipart":       "a multipart/form-data body without a boundary, or whose parts are not laid out between `--boundary` delimiters",
	"bad-graphql":         "a GraphQL request (GRAPHQL method or X-REQUEST-TYPE: GraphQL) without a query, or whose variables block is not a JSON object",
	"bad-save-path":       "a `>> file` after the body with no path, a path outside the project, or a second one on the same request",
	"missing-schema-file": "a `# @assert … matchesSchema <file>` whose schema file does not exist or lies outside the project",
}

Codes are the diagnostic codes apic reports, with a one-line description each. They are part of the `validate --json` contract: a code never changes meaning, and new ones are only added.

View Source
var KnownDirectives = map[string]string{
	"name":        "request name used on the command line",
	"description": "one-line description shown by list/describe",
	"capture":     "store a response value: `# @capture name = selector`",
	"assert":      "assert on the response: `# @assert selector op value`",
	"auth":        "authentication: `# @auth bearer|basic|aws|oauth2|exec|none ...`",
	"step":        "Gherkin phrase that runs this request: `# @step a user named {name} exists`",
	"ref":         "run another request first when a variable is missing: `# @ref login`",
	"forceRef":    "run another request first, every time: `# @forceRef login`",
	"no-redirect": "do not follow redirects",
	"no-session":  "do not persist captures from this request",
	"no-cookies":  "send no cookies with this request and keep none it sets",
	"timeout":     "per-request timeout, e.g. `10s`",
	"retry":       "re-send until the assertions pass: `# @retry <attempts> [interval]`, e.g. `# @retry 10 2s`",
	"sleep":       "wait before sending, e.g. `# @sleep 2s`",
	"disabled":    "skip the request when its file runs as a flow; `apic run <name>` still sends it",
	"note":        "free text, ignored (REST Client compatibility)",
	"prompt":      "REST Client prompt, ignored (pass with --var instead)",
}

KnownDirectives are the `# @key` directives apic understands. Others are reported as warnings by validate but otherwise ignored.

Functions

func Format

func Format(src string) string

Format rewrites .http content in its canonical form. It works on the lines rather than the AST so that everything the parser skips (comments, unknown directives, editor script blocks) is kept verbatim:

  • one blank line between blocks, `### Title` on its own line;
  • directives in a fixed order (name, description, step, auth, ref, forceRef, retry, timeout, no-redirect, no-session, no-cookies, assert, capture, then unknown ones as written), each `# @key value`; comments keep their place among the directives;
  • `@name = value` file variables with single spaces;
  • the request line with single spaces, query continuations indented four spaces, header names in canonical case;
  • a JSON body pretty-printed with two spaces when it parses and holds no {{placeholders}}; every other body byte for byte as written, since the body is what the request sends;
  • trailing whitespace removed outside bodies, blank lines after a body dropped, one final newline.

Formatting is idempotent: Format(Format(s)) == Format(s).

func FormatRequest

func FormatRequest(src, name string) (out string, ok bool)

FormatRequest formats one request of a file and leaves every other byte as written: the request whose `# @name` is name, or the n-th request of the file when name is a number, counted as the parser and so `apic run file.http#3` count them (the text before the first `###` is a request when it holds a request line; a `###` block without one is not). ok is false when nothing matches. It is for an agent (or an editor) that added or changed one request in a file it does not own, so the change stays that request's.

func GraphQLEnvelope

func GraphQLEnvelope(query, variables string) (string, error)

GraphQLEnvelope is the body sent for a GraphQL request: the query as a JSON string and the variables object, when there is one. The variables must be a JSON object by then.

func Parse

func Parse(path, content string) (*File, []Diagnostic)

Parse parses .http content. path is used only for diagnostics and IDs.

func ParseFile

func ParseFile(path string) (*File, []Diagnostic, error)

ParseFile reads and parses a .http file from disk.

func ParseRetry

func ParseRetry(s string) (n int, interval time.Duration, err error)

ParseRetry parses a retry policy, "<attempts> [interval]": how many times to send a request until its assertions pass, and how long to wait between attempts (a Go duration such as 500ms or 2s; default 1s). Attempts must be at least 1. It is the value of `# @retry`, of `--retry` and of retry in apic.yaml.

func ParseSleep

func ParseSleep(s string) (time.Duration, error)

ParseSleep reads the value of `# @sleep`: a Go duration such as 500ms or 2s, not negative.

func QuoteParam

func QuoteParam(s string) string

QuoteParam quotes a Content-Disposition parameter value the way RFC 2616 quoted-strings are written: only backslash and the double quote are escaped, so a non-ASCII name or filename survives mime.ParseMediaType (Go's %q would write \u escapes it reads as literal letters).

func Span

func Span(line, sub string, after int) (col, end int)

Span returns the 1-based byte columns [col, end) of sub within line, or zeros when sub is empty or not found. after is the offset to start searching from, so a value that also appears in the directive key is found in the right place.

func SplitGraphQL

func SplitGraphQL(body string) (query, variables string)

SplitGraphQL separates a GraphQL body into the query and the variables: the variables are the JSON object after the last blank line, when what follows that line starts with `{`. The variables are "" when there are none. Both halves keep their placeholders.

func ValidCaptureName

func ValidCaptureName(name string) bool

ValidCaptureName reports whether name is one `# @capture` would accept.

Types

type Assert

type Assert struct {
	Expr   string
	Line   int
	Column int
}

Assert is a raw assertion expression: `# @assert status == 200`. Column is where Expr starts on the line.

type Capture

type Capture struct {
	Name     string
	Selector string
	Line     int
	Column   int
}

Capture declares that a value selected from the response should be stored under Name for later requests: `# @capture token = body.$.access_token`. Column is where Selector starts on the line.

type Diagnostic

type Diagnostic struct {
	Path      string `json:"path"`
	Line      int    `json:"line"`
	Column    int    `json:"column,omitempty"`
	EndLine   int    `json:"end_line,omitempty"`
	EndColumn int    `json:"end_column,omitempty"`
	Severity  string `json:"severity"` // "error" or "warning"
	Code      string `json:"code,omitempty"`
	Message   string `json:"message"`
}

Diagnostic is a non-fatal problem found while parsing or validating.

Line and Column are 1-based; Column counts bytes from the start of the line. EndLine and EndColumn mark the end of the span, exclusive, so a diagnostic on the word "nope" at column 12 has EndColumn 16. The columns are zero when the problem has no useful span (a whole file, or apic.yaml). Code is a stable identifier from Codes that tools can key fixes on.

func (Diagnostic) String

func (d Diagnostic) String() string

type Directive

type Directive struct {
	Key    string
	Value  string
	Line   int
	Column int
}

Directive is a `# @key value` comment placed before a request line. Column is the 1-based byte column where Value starts on the line, or where `@key` starts when there is no value.

type File

type File struct {
	Path     string
	Vars     []Var
	Requests []*Request
}

File is a parsed .http file.

type FileRef

type FileRef struct {
	Path      string
	Templated bool
	Line      int
	Column    int
}

FileRef is a `< path` or `<@ path` reference in a request: the whole body, or one part of a multipart body.

type Header struct {
	Name  string
	Value string
}

Header is a raw, un-templated request header.

type Multipart

type Multipart struct {
	Boundary string
	Parts    []Part
}

Multipart is a parsed multipart/form-data body.

func (*Multipart) Files

func (m *Multipart) Files() int

Files counts the parts whose content comes from a file.

type Part

type Part struct {
	Headers     []Header
	Name        string // from Content-Disposition
	Filename    string // from Content-Disposition, when the part is a file
	ContentType string // the part's own Content-Type header, when present
	Body        string // literal content (a template), empty when File is set
	File        string // `< path`: the file whose bytes are the content
	// FileTemplated is `<@ path`: substitute {{vars}} inside the file too.
	FileTemplated bool
	FileLine      int // line of the `< path` reference
	FileColumn    int // column where the path starts on that line
	Line          int // line of the delimiter that opens the part
}

Part is one part of a multipart/form-data body, as written in the file: its headers, then either literal content or a `< file` reference.

type Ref

type Ref struct {
	ID     string
	Force  bool
	Line   int
	Column int // column where the target starts
}

Ref is a `# @ref` or `# @forceRef` directive: another request to run before this one. A ref runs only when this request is missing a variable; a forceRef runs every time.

type Request

type Request struct {
	File              *File
	Index             int    // 1-based position within the file
	Name              string // from `# @name`, may be empty
	Title             string // free text after `###`
	Description       string // from `# @description`, else Title
	Directives        []Directive
	Captures          []Capture
	Asserts           []Assert
	Method            string
	URL               string // raw template
	HTTPVersion       string
	Headers           []Header
	Body              string  // raw template, empty when none
	BodyLine          int     // line of the first body line, 0 when there is no body
	BodyFile          string  // set when the body is `< ./file`
	BodyFileTemplated bool    // `<@ ./file`: substitute {{vars}} inside the file too
	BodyFileLine      int     // line of the `< ./file` reference, for diagnostics
	BodyFileColumn    int     // column where the path starts on that line
	SaveTo            *SaveTo // `>> ./file` after the body: where the response body goes
	Line              int     // line number of the request line
}

Request is one request block within a file.

func (*Request) BodyFiles

func (r *Request) BodyFiles() []FileRef

BodyFiles returns every file the request's body reads: the whole-body `< file`, or the `< file` parts of a multipart body. A multipart body that does not parse contributes nothing; validate reports it.

func (*Request) Directive

func (r *Request) Directive(key string) (string, bool)

Directive returns the value of the first directive with the given key.

func (*Request) DirectiveSpan

func (r *Request) DirectiveSpan(key string) (line, col, end int)

DirectiveSpan returns the line and the [col, end) columns of the value of the first directive with the given key, or zeros when there is none.

func (*Request) Disabled

func (r *Request) Disabled() bool

Disabled reports `# @disabled`: the request is skipped when its file runs as a flow, and still sent when it is asked for by name.

func (*Request) GraphQL

func (r *Request) GraphQL() (query, variables string, err error)

GraphQL returns the query and the variables of a GraphQL request as written, and an error when the request has no query or the variables hold no placeholders and are not a JSON object.

func (*Request) Header

func (r *Request) Header(name string) (string, bool)

Header returns the value of the first header with the given name, case-insensitively.

func (*Request) ID

func (r *Request) ID() string

ID returns the stable identifier used on the command line: the request's name when it has one, else `<file>#<index>`.

func (*Request) IsGraphQL

func (r *Request) IsGraphQL() bool

IsGraphQL reports whether the request is written as a GraphQL query: the `GRAPHQL` method, or an `X-REQUEST-TYPE: GraphQL` header.

func (*Request) IsMultipart

func (r *Request) IsMultipart() bool

IsMultipart reports whether the request declares a multipart/form-data Content-Type. The body then holds parts (see Multipart) rather than one template.

func (*Request) Multipart

func (r *Request) Multipart() (*Multipart, error)

Multipart parses the body of a multipart/form-data request into its parts. It returns nil, nil for a request that is not multipart, or whose whole body is a `< file`; an error names what is wrong with the body.

func (*Request) Protocol

func (r *Request) Protocol() (string, error)

Protocol is the HTTP version the request line asks for: "" when it names none, HTTP1 (HTTP/1.0 is sent as 1.1) or HTTP2. HTTP/3 and anything else is an error, which validate reports as bad-http-version.

func (*Request) Refs

func (r *Request) Refs() []Ref

Refs returns every `# @ref` and `# @forceRef` declared on the request, in order.

func (*Request) Sleep

func (r *Request) Sleep() (time.Duration, error)

Sleep is how long `# @sleep <duration>` waits before the request is sent; zero without the directive.

func (*Request) Steps

func (r *Request) Steps() []string

Steps returns every `# @step` phrase declared on the request.

type SaveTo

type SaveTo struct {
	Path      string
	Overwrite bool
	Line      int
	Column    int
}

SaveTo is a `>> ./file` (create) or `>>! ./file` (overwrite) line after the body: the response body is written there, relative to the `.http` file. Column is where the path starts on the line.

type Var

type Var struct {
	Name  string
	Value string
	Line  int
}

Var is a file-level variable declared as `@name = value`.

Jump to

Keyboard shortcuts

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