hargo

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 28 Imported by: 0

README

Hargo

CI Go Reference Go Report Card GitHub license GitHub issues Twitter

Hargo parses HAR files, can convert to curl format, and serve as a load test driver.

NAME:
   hargo - work with HTTP Archive (.har) files

USAGE:
   hargo <command> [arguments] <.har file>

VERSION:
   0.2.0

AUTHOR:
   Mark A. Richman <mark@markrichman.com>

COMMANDS:
     fetch, f     Fetch URLs in .har
     curl, c      Convert .har to curl
     run, r       Run .har file
     validate, v  Validate .har file
     dump, d      Dump .har file
     load, l      Load test .har file
     help, h      Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --debug        Show debug output
   --help, -h     show help
   --version, -v  print the version

COPYRIGHT:
   (c) 2024 Mark A. Richman

Installing

go install github.com/mrichman/hargo/v2/cmd/hargo@latest

Note the /v2 suffix: it is part of the module path, so omitting it installs the much older v1 release.

To use hargo as a library:

go get github.com/mrichman/hargo/v2
import "github.com/mrichman/hargo/v2"

Every entry point reads from an io.Reader and takes an options struct, the operations that do network I/O take a context.Context, and the library writes nothing and logs nothing unless you ask it to:

// Replay a HAR, printing progress and logging skipped entries.
err := hargo.Run(ctx, f, hargo.RunOptions{
	NoWait:   true,
	Logger:   slog.Default(),
	Progress: os.Stdout,
})

Any operation can be limited to a subset of the entries, and a load test can report its own figures:

// Load test only the API calls, and collect the summary.
var summary hargo.LoadSummary
err := hargo.LoadTest(ctx, f, hargo.LoadTestOptions{
	Workers:  10,
	Duration: 30 * time.Second,
	Filter:   hargo.EntryFilter{URL: `/api/`, Method: []string{"POST"}},
	Summary:  &summary,
})
fmt.Println(summary.Requests, summary.P95, summary.ErrorRate)

Upgrading from v1? See MIGRATING.md.

Building and Running Hargo

Hargo requires Go 1.27.1 or newer.

git clone https://github.com/mrichman/hargo.git
cd hargo
make install
hargo validate testdata/golang.org.har

Run make help to see every target, or make check to run the same checks CI runs. A justfile mirrors every target if you prefer just — run just to list the recipes. See CONTRIBUTING.md for the development workflow.

About HAR Files

If you use Google Chrome, you can record these files by following the steps below:

  1. Right-click anywhere on that page and click on Inspect Element to open Chrome's Developer Tools
  2. The Developer Tools will open as a panel at the bottom of the page. Click on the Network tab.
  3. Click the Record button, which is the solid black circle at the bottom of the Network tab, and you'll start recording activity in your browser.
  4. Refresh the page and start working normally
  5. Right-click within the Network tab and click Save as HAR with Content to save a copy of the activity that you recorded.
  6. Within the file window, save the HAR file.

Commands

Selecting entries

Every command that reads entries accepts the same three filter flags, which combine — an entry must match all of the criteria you give:

hargo dump foo.har --url '/api/'            # unanchored regular expression
hargo run foo.har --method POST            # repeatable
hargo curl foo.har --status 200 --status 204
hargo load foo.har --url '\.js$' --method GET

--url is a regular expression rather than a glob, because a glob's * does not cross /, so the intuitive *.js would match no full URL at all. A pattern that does not compile is reported as an error rather than quietly matching nothing.

Fetch

The fetch command downloads all resources references in .har file:

hargo fetch foo.har

This will produce a directory named hargo-fetch-yyyymmddhhmmss containing all assets references by the .har file. This is similar to what you'd see when invoking wget on a particular URL.

Pass an output directory to use it instead of a timestamped one:

hargo fetch foo.har ./assets

Compressed responses are decompressed before being written, and entries whose paths share a filename are saved as name.ext, name-1.ext, and so on rather than overwriting each other.

A resource that cannot be fetched is reported and skipped, so one broken URL does not abandon the rest. hargo fetch exits non-zero if any entry failed.

Curl

The curl command will output a curl command line for each entry in the .har file.

hargo curl foo.har

Write to a file instead of stdout with -o:

hargo curl foo.har -o requests.sh

The output is rendered before the file is created, so a malformed .har file leaves no truncated file behind.

Run

The run command executes each request in the .har file, in the order and with the timing they were recorded:

hargo run foo.har

Recorded delays can be compressed or dropped, which matters for HARs that span minutes of real time:

hargo run --speed 4 foo.har          # replay four times faster
hargo run --no-wait foo.har          # ignore the delays entirely
hargo run --max-delay 2s foo.har     # cap any single wait at two seconds

An entry that cannot be built or sent is reported and skipped, so one broken request does not abandon the rest. hargo run exits non-zero if any entry failed.

By default any response the server actually returned counts as a success, since a recorded 404 is often the expected result. To treat an error status as a failure:

hargo run foo.har --fail-on-status

This is similar to fetch but will not save any output.

Validate

The validate command will report any errors in the format of a .har file.

hargo validate foo.har

HAR file format is defined here: https://w3c.github.io/web-performance/specs/HAR/Overview.html

Dump

Dump prints information about all HTTP requests in .har file

hargo dump foo.har

Write to a file instead of stdout with -o:

hargo dump foo.har -o report.txt

Load

Hargo can act as a load test agent. Given a .har file, hargo can spawn a number of concurrent workers to repeat each HTTP request in order. By default, hargo will spawn 10 workers and run for a duration of 60 seconds.

Hargo will also save its results to InfluxDB, if available. Each HTTP response is stored as a point of time-series data, which can be graphed by Chronograf, Grafana, or similar visualization tool for analysis.

When the test finishes, hargo prints a summary:

Load test complete.
  requests    83198 in 2.998s (27747.0/sec)
  failures    0 (0.0%)
  latency     min 37µs  p50 120µs  p95 264µs  p99 420µs  max 7.9ms
  status      200=83198

The percentiles are exact rather than bucketed, and the elapsed time is measured rather than assumed from -d, so a test cut short reports what actually happened. The summary is printed whether or not InfluxDB is configured.

Docker

Build container
docker build -t hargo .
Run container
docker run --rm -v `pwd`/testdata:/testdata hargo hargo run /testdata/golang.org.har

Docker-compose

The example docker-compose file will start three containers:

  • hargo
  • influxdb
  • grafana

The hargo container will first needs to be built. See build. When the compose file is run it will start a hargo load process that will write the results to InfluxDB. This InfluxDB instance can be viewed using the grafana container. This contains an example dashboard showing the latency of the executed request. Username/password for all the containers is hargo/hargo.

commands
cd example/docker-compose
docker-compose up
docker-compose down -v

Documentation

Overview

Package hargo reads, validates, and replays HTTP Archive (.har) files.

A HAR file is a JSON log of HTTP transactions, exported by browser developer tools and HTTP proxies. This package parses that log into Go types and offers several ways to work with it:

  • Validate checks that the input parses and declares a supported version.
  • Decode parses a HAR into a HAR value, dropping WebSocket entries and ordering the remainder by start time.
  • Dump and DumpTo print a human-readable summary of every entry.
  • ToCurl converts each entry into an equivalent curl command line.
  • Run replays every entry in sequence, honouring the recorded delays.
  • Fetch downloads every referenced resource to disk.
  • LoadTest replays entries concurrently, optionally recording results to InfluxDB.

Every entry point takes an io.Reader and skips a leading UTF-8 byte order mark if one is present.

This package writes nothing and logs nothing by default. The operations that can report progress take an options struct with a Logger and a Progress writer; leaving either nil discards that output.

Index

Constants

View Source
const HARVersion = "1.2"

HARVersion is the only HAR specification version this package supports.

Variables

This section is empty.

Functions

func Dump

func Dump(r io.Reader, opts DumpOptions) error

Dump writes a human-readable summary of the selected entries in a HAR document to stdout.

func DumpTo

func DumpTo(w io.Writer, r io.Reader, opts DumpOptions) error

DumpTo writes a human-readable summary of the selected entries in a HAR document to w.

func EntryToRequest

func EntryToRequest(ctx context.Context, entry *Entry, opts EntryOptions) (*http.Request, error)

EntryToRequest converts a HAR entry into an http.Request bound to ctx.

func Fetch

func Fetch(ctx context.Context, r io.Reader, opts FetchOptions) error

Fetch downloads every resource referenced by a HAR document.

An entry that cannot be built or downloaded is reported to opts.Logger and skipped, so one bad resource does not abandon the rest; Fetch then returns an error naming how many failed. Cancelling ctx stops the download.

func LoadTest

func LoadTest(ctx context.Context, r io.ReadSeeker, opts LoadTestOptions) error

LoadTest replays the entries in a HAR document concurrently until ctx is cancelled or opts.Duration elapses, recording the result of every request.

r is read repeatedly from the start, so the test can run for longer than the recording.

func NewReader

func NewReader(r io.Reader) *bufio.Reader

NewReader returns a bufio.Reader that skips an initial UTF-8 byte order mark. The parsing entry points apply this themselves, so callers rarely need it.

https://tools.ietf.org/html/rfc7159#section-8.1

func ParseEntryTime

func ParseEntryTime(s string) (time.Time, error)

ParseEntryTime parses a HAR startedDateTime.

A caller that ignores the error gets the zero time, which is why the replaying operations report it instead: treating an unparseable timestamp as year one makes the gap to the next entry astronomically large.

func ReadStream

func ReadStream(ctx context.Context, r io.ReadSeeker, entries chan<- Entry, opts ReadOptions) error

ReadStream decodes the entries of a HAR document and sends the selected ones on entries, replaying r from the start each time it reaches the end so that a load test can run for longer than the recording. It closes entries before returning.

ReadStream returns ctx.Err() when ctx is cancelled, nil when r holds no usable entries, and a descriptive error when r cannot be decoded or when a filter selects none of the entries it did find. Streaming avoids holding the whole document in memory.

https://golang.org/pkg/encoding/json/#example_Decoder_Decode_stream

func Run

func Run(ctx context.Context, r io.Reader, opts RunOptions) error

Run replays every entry in a HAR document, honouring the recorded delays unless opts says otherwise.

An entry that cannot be built or sent is reported to opts.Logger and skipped, so one bad entry does not abandon the replay; Run then returns an error naming how many failed. Cancelling ctx stops the replay.

func ToCurl

func ToCurl(r io.Reader, opts CurlOptions) (string, error)

ToCurl converts the entries a HAR document to curl command lines.

curl -X <method> -b '<name=value; name=value...>' -H '<name: value>' ... -d '<postData>' <url>.

For a large HAR prefer ToCurlTo, which streams instead of assembling the whole output in memory.

func ToCurlTo

func ToCurlTo(w io.Writer, r io.Reader, opts CurlOptions) error

ToCurlTo writes a curl command line for each selected entry to w.

func Validate

func Validate(r io.Reader) error

Validate reports whether r contains a usable HAR log, returning a descriptive error when it does not.

It checks that the document parses, declares a supported version, and carries the fields the rest of this package relies on: an entries array, and for each entry a parseable startedDateTime and a request with a method and a usable URL. A document that passes can be replayed by Run without surprises.

Types

type Browser

type Browser struct {
	// Required. The name of the browser that created the log.
	Name string `json:"name"`
	// Required. The version number of the browser that created the log.
	Version string `json:"version"`
	// Optional. A comment provided by the user or the browser.
	Comment string `json:"comment"`
}

Browser that created the log.

type Cache

type Cache struct {
	// optional State of a cache entry before the request. Leave out this field
	// if the information is not available.
	BeforeRequest CacheObject `json:"beforeRequest,omitempty"`
	// optional State of a cache entry after the request. Leave out this field if
	// the information is not available.
	AfterRequest CacheObject `json:"afterRequest,omitempty"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Cache contains info about a request coming from browser cache.

type CacheObject

type CacheObject struct {
	// optional - Expiration time of the cache entry.
	Expires string `json:"expires,omitempty"`
	// The last time the cache entry was opened.
	LastAccess string `json:"lastAccess"`
	// Etag
	ETag string `json:"eTag"`
	// The number of times the cache entry has been opened.
	HitCount int `json:"hitCount"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

CacheObject is used by both beforeRequest and afterRequest.

type Content

type Content struct {
	// Length of the returned content in bytes. Should be equal to
	// response.bodySize if there is no compression and bigger when the content
	// has been compressed.
	Size int `json:"size"`
	// optional Number of bytes saved. Leave out this field if the information
	// is not available.
	Compression int `json:"compression,omitempty"`
	// MIME type of the response text (value of the Content-Type response
	// header). The charset attribute of the MIME type is included (if
	// available).
	MimeType string `json:"mimeType"`
	// optional Response body sent from the server or loaded from the browser
	// cache. This field is populated with textual content only. The text field
	// is either HTTP decoded text or a encoded (e.g. "base64") representation of
	// the response body. Leave out this field if the information is not
	// available.
	Text string `json:"text,omitempty"`
	// optional (new in 1.2) Encoding used for response text field e.g
	// "base64". Leave out this field if the text field is HTTP decoded
	// (decompressed & unchunked), than trans-coded from its original character
	// set into UTF-8.
	Encoding string `json:"encoding,omitempty"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
	// optional (community enhancement) A path to an attached file containing this content
	// used by Playwright
	File string `json:"_file,omitempty"`
}

Content describes details about response content (embedded in <response> object).

type Cookie struct {
	// The name of the cookie.
	Name string `json:"name"`
	// The cookie value.
	Value string `json:"value"`
	// optional The path pertaining to the cookie.
	Path string `json:"path,omitempty"`
	// optional The host of the cookie.
	Domain string `json:"domain,omitempty"`
	// optional Cookie expiration time.
	// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD, e.g. 2009-07-24T19:20:30.123+02:00).
	Expires string `json:"expires,omitempty"`
	// optional Set to true if the cookie is HTTP only, false otherwise.
	HTTPOnly bool `json:"httpOnly,omitempty"`
	// optional (new in 1.2) True if the cookie was transmitted over ssl, false
	// otherwise.
	Secure bool `json:"secure,omitempty"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Cookie contains list of all cookies (used in <request> and <response> objects).

type Creator

type Creator struct {
	// Required. The name of the application that created the log.
	Name string `json:"name"`
	// Required. The version number of the application that created the log.
	Version string `json:"version"`
	// Optional. A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Creator contains information about the log creator application.

type CurlOptions

type CurlOptions struct {
	// Filter selects which entries to convert. A zero Filter selects all of them.
	Filter EntryFilter
}

CurlOptions controls how a HAR is converted to curl command lines. The zero value converts every entry.

type DumpOptions

type DumpOptions struct {
	// Filter selects which entries to dump. A zero Filter selects all of them.
	Filter EntryFilter
}

DumpOptions controls how a HAR is summarised. The zero value dumps every entry.

type Entry

type Entry struct {
	Pageref string `json:"pageref,omitempty"`
	// Date and time stamp of the request start
	// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD).
	StartedDateTime string `json:"startedDateTime"`
	// Total elapsed time of the request in milliseconds. This is the sum of all
	// timings available in the timings object (i.e. not including -1 values) .
	Time float64 `json:"time"`
	// Detailed info about the request.
	Request Request `json:"request"`
	// Detailed info about the response.
	Response Response `json:"response"`
	// Info about cache usage.
	Cache Cache `json:"cache"`
	// Detailed timing info about request/response round trip. The HAR spec names
	// this field "timings"; "pageTimings" belongs to a page, not an entry.
	Timings Timings `json:"timings"`
	// optional (new in 1.2) IP address of the server that was connected
	// (result of DNS resolution).
	ServerIPAddress string `json:"serverIPAddress,omitempty"`
	// optional (new in 1.2) Unique ID of the parent TCP/IP connection, can be
	// the client port number. Note that a port number doesn't have to be unique
	// identifier in cases where the port is shared for more connections. If the
	// port isn't available for the application, any other unique connection ID
	// can be used instead (e.g. connection index). Leave out this field if the
	// application doesn't support this info.
	Connection string `json:"connection,omitempty"`
	// (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Entry is a unique, optional Reference to the parent page. Leave out this field if the application does not support grouping by pages.

type EntryFilter

type EntryFilter struct {
	// URL is an unanchored regular expression matched against the full request
	// URL. An empty URL matches any URL.
	//
	// A regular expression rather than a glob: a glob's * does not cross /, so
	// the intuitive "*.js" would match no full URL at all.
	URL string

	// Method restricts the selection to these HTTP methods, compared
	// case-insensitively. An empty Method matches any method.
	Method []string

	// Status restricts the selection to these response status codes, as recorded
	// in the HAR. An empty Status matches any status.
	//
	// This is always the recorded status, never a live one: the operations that
	// replay entries cannot know a status before sending the request, and the
	// operations that only read a HAR have nothing else available.
	Status []int
	// contains filtered or unexported fields
}

EntryFilter selects a subset of HAR entries. A zero EntryFilter matches everything, and every criterion that is set must match.

func (*EntryFilter) IsZero

func (f *EntryFilter) IsZero() bool

IsZero reports whether f selects everything.

func (*EntryFilter) Match

func (f *EntryFilter) Match(e Entry) bool

Match reports whether e satisfies every criterion set on f.

compile must have been called first; an uncompiled URL pattern is treated as matching nothing rather than panicking.

type EntryOptions

type EntryOptions struct {
	// IgnoreHARCookies drops the cookies recorded in the HAR entry.
	IgnoreHARCookies bool
}

EntryOptions controls how a HAR entry is turned into an http.Request.

type FetchOptions

type FetchOptions struct {
	// OutDir is the directory to write into, created if necessary. When empty a
	// directory named hargo-fetch-<timestamp> is created in the working
	// directory.
	OutDir string

	// AcceptErrorStatus saves the response body even when the server reported an
	// error status. By default a 4xx or 5xx response is treated as a failed
	// download and nothing is written, so the output directory does not fill with
	// error pages named after the resources they failed to be.
	AcceptErrorStatus bool

	// Filter selects which entries to download. A zero Filter selects all of them.
	// Entries are selected before downloading begins, so the failure tally counts
	// only the entries actually attempted.
	Filter EntryFilter

	// Logger receives diagnostics about skipped and failed entries. A nil
	// Logger discards them.
	Logger *slog.Logger

	// Progress receives one line per resource. A nil Progress discards it.
	Progress io.Writer
}

FetchOptions controls how Fetch downloads the resources a HAR references. The zero value writes to a new timestamped directory in the working directory and produces no output.

type HAR

type HAR struct {
	Log Log `json:"log"`
}

HAR is a container type for deserialization.

func Decode

func Decode(r io.Reader) (HAR, error)

Decode reads a HAR document from r and returns it.

WebSocket entries are removed because an http.Client cannot dial them, and the remaining entries are ordered by their recorded start time.

type LoadSummary

type LoadSummary struct {
	// Requests is how many results were recorded.
	Requests int

	// Failures counts results that either never completed or returned a status of
	// 400 or above.
	Failures int

	// ErrorRate is Failures divided by Requests, or 0 when nothing ran.
	ErrorRate float64

	// Elapsed is the measured wall clock time of the test. It is not the
	// configured duration, because a cancelled run ends early.
	Elapsed time.Duration

	// RequestsPerSec is Requests divided by Elapsed.
	RequestsPerSec float64

	// Latency distribution across every recorded result.
	Min, P50, P95, P99, Max time.Duration

	// StatusCounts counts results by status code. A key of 0 means the request
	// never completed.
	StatusCounts map[int]int
}

LoadSummary reports what a load test observed. A caller obtains one by setting LoadTestOptions.Summary.

type LoadTestOptions

type LoadTestOptions struct {
	// HARFile labels the results with the name of the file under test.
	HARFile string

	// Workers is how many concurrent workers to run. Zero or unset means 1.
	Workers int

	// Duration bounds the test. Zero means run until ctx is cancelled.
	Duration time.Duration

	// InfluxDBURL is where results are recorded. A nil URL discards them.
	InfluxDBURL *url.URL

	// IgnoreHARCookies drops the cookies recorded in the HAR.
	IgnoreHARCookies bool

	// InsecureSkipVerify disables TLS certificate verification.
	InsecureSkipVerify bool

	// Filter selects which entries to replay. A zero Filter selects all of them.
	// A filter that selects none of the entries present is an error rather than a
	// silently empty run.
	Filter EntryFilter

	// Results, when non-nil, receives a copy of every result. LoadTest does not
	// close it. A caller that supplies this channel must keep reading from it
	// for the duration of the test, or the workers will block.
	Results chan<- TestResult

	// Summary, when non-nil, receives the figures for the completed test. It is
	// filled in just before LoadTest returns, whether or not results were also
	// recorded to InfluxDB.
	Summary *LoadSummary

	// Logger receives diagnostics about failed requests. A nil Logger discards
	// them.
	Logger *slog.Logger

	// Progress receives one line per request. A nil Progress discards it.
	//
	// Writes are serialized internally, so it need not be safe for concurrent use
	// even though the workers run in parallel.
	Progress io.Writer
}

LoadTestOptions controls how LoadTest drives a HAR file. The zero value runs a single worker until ctx is cancelled, discarding results.

type Log

type Log struct {

	// Required. Version number of the format.
	Version string `json:"version"`
	// Required. An object of type creator that contains the name and version
	// information of the log creator application.
	Creator Creator `json:"creator"`
	// Optional. An object of type browser that contains the name and version
	// information of the user agent.
	Browser Browser `json:"browser"`
	// Optional. An array of objects of type page, each representing one exported
	// (tracked) page. Leave out this field if the application does not support
	// grouping by pages.
	Pages []Page `json:"pages,omitempty"`
	// Required. An array of objects of type entry, each representing one
	// exported (tracked) HTTP request.
	Entries []Entry `json:"entries"`
	// Optional. A comment provided by the user or the application. Sorting
	// entries by startedDateTime (starting from the oldest) is preferred way how
	// to export data since it can make importing faster. However the reader
	// application should always make sure the array is sorted (if required for
	// the import).
	Comment string `json:"comment"`
}

Log represents the root of the exported data. This object MUST be present and its name MUST be "log".

type NVP

type NVP struct {
	Name    string `json:"name"`
	Value   string `json:"value"`
	Comment string `json:"comment,omitempty"`
}

NVP is simply a name/value pair with a comment.

type Page

type Page struct {

	// Date and time stamp for the beginning of the page load
	// (ISO 8601 YYYY-MM-DDThh:mm:ss.sTZD, e.g. 2009-07-24T19:20:30.45+01:00).
	StartedDateTime string `json:"startedDateTime"`
	// Unique identifier of a page within the . Entries use it to refer the parent page.
	ID string `json:"id"`
	// Page title.
	Title string `json:"title"`
	// Detailed timing info about page load.
	PageTimings PageTimings `json:"pageTimings"`
	// (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Page object for every exported web page and one <entry> object for every HTTP request. In case when an HTTP trace tool isn't able to group requests by a page, the <pages> object is empty and individual requests doesn't have a parent page.

type PageTimings

type PageTimings struct {
	// Content of the page loaded. Number of milliseconds since page load started
	// (page.startedDateTime). Use -1 if the timing does not apply to the current
	// request.
	// Depeding on the browser, onContentLoad property represents DOMContentLoad
	// event or document.readyState == interactive.
	OnContentLoad float64 `json:"onContentLoad"`
	// Page is loaded (onLoad event fired). Number of milliseconds since page
	// load started (page.startedDateTime). Use -1 if the timing does not apply
	// to the current request.
	OnLoad float64 `json:"onLoad"`
	// (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment"`
}

PageTimings describes timings for various events (states) fired during the page load. All times are specified in milliseconds. If a time info is not available appropriate field is set to -1.

Values are fractional; recorders emit numbers such as 171.71799996867776.

type PostData

type PostData struct {
	//  Mime type of posted data.
	MimeType string `json:"mimeType"`
	//  List of posted parameters (in case of URL encoded parameters).
	Params []PostParam `json:"params"`
	//  Plain text posted data
	Text string `json:"text"`
	// optional (new in 1.2) A comment provided by the user or the
	// application.
	Comment string `json:"comment,omitempty"`
}

PostData describes posted data, if any (embedded in <request> object).

type PostParam

type PostParam struct {
	// name of a posted parameter.
	Name string `json:"name"`
	// optional value of a posted parameter or content of a posted file.
	Value string `json:"value,omitempty"`
	// optional name of a posted file.
	FileName string `json:"fileName,omitempty"`
	// optional content type of a posted file.
	ContentType string `json:"contentType,omitempty"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

PostParam is a list of posted parameters, if any (embedded in <postData> object).

type ReadOptions

type ReadOptions struct {
	// Filter selects which entries to deliver. A zero Filter selects all of them.
	Filter EntryFilter

	// Logger receives diagnostics. A nil Logger discards them.
	Logger *slog.Logger
}

ReadOptions controls how ReadStream decodes and selects entries. The zero value streams every entry and produces no output.

type Request

type Request struct {
	// Request method (GET, POST, ...).
	Method string `json:"method"`
	// Absolute URL of the request (fragments are not included).
	URL string `json:"url"`
	// Request HTTP Version.
	HTTPVersion string `json:"httpVersion"`
	// List of cookie objects.
	Cookies []Cookie `json:"cookies"`
	// List of header objects.
	Headers []NVP `json:"headers"`
	// List of query parameter objects.
	QueryString []NVP `json:"queryString"`
	// Posted data.
	PostData PostData `json:"postData"`
	// Total number of bytes from the start of the HTTP request message until
	// (and including) the double CRLF before the body. Set to -1 if the info
	// is not available.
	//
	// The HAR spec names this field "headersSize", matching Response.
	HeadersSize int `json:"headersSize"`
	// Size of the request body (POST data payload) in bytes. Set to -1 if the
	// info is not available.
	BodySize int `json:"bodySize"`
	// (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment"`
}

Request contains detailed info about performed request.

type Response

type Response struct {
	// Response status.
	Status int `json:"status"`
	// Response status description.
	StatusText string `json:"statusText"`
	// Response HTTP Version.
	HTTPVersion string `json:"httpVersion"`
	// List of cookie objects.
	Cookies []Cookie `json:"cookies"`
	// List of header objects.
	Headers []NVP `json:"headers"`
	// Details about the response body.
	Content Content `json:"content"`
	// Redirection target URL from the Location response header.
	RedirectURL string `json:"redirectURL"`
	// Total number of bytes from the start of the HTTP response message until
	// (and including) the double CRLF before the body. Set to -1 if the info is
	// not available.
	// The size of received response-headers is computed only from headers that
	// are really received from the server. Additional headers appended by the
	// browser are not included in this number, but they appear in the list of
	// header objects.
	HeadersSize int `json:"headersSize"`
	// Size of the received response body in bytes. Set to zero in case of
	// responses coming from the cache (304). Set to -1 if the info is not
	// available.
	BodySize int `json:"bodySize"`
	// optional (new in 1.2) A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Response contains detailed info about the response.

type RunOptions

type RunOptions struct {
	// IgnoreHARCookies drops the cookies recorded in the HAR.
	IgnoreHARCookies bool

	// InsecureSkipVerify disables TLS certificate verification.
	InsecureSkipVerify bool

	// Speed scales the recorded delay between entries: 1 replays in real time
	// and 2 replays twice as fast. Zero or unset means 1, so that the zero value
	// of RunOptions replays in real time. Negative values are rejected.
	//
	// Speed cannot express "no delay at all" because 0 is the zero value; use
	// NoWait for that.
	Speed float64

	// NoWait issues every request back to back, ignoring the recorded timings
	// entirely. It takes precedence over Speed and MaxDelay.
	NoWait bool

	// MaxDelay caps the wait before any single entry, applied after Speed. Zero
	// means no cap. Useful for HARs containing minutes of user idle time.
	MaxDelay time.Duration

	// Filter selects which entries to replay. A zero Filter selects all of them.
	// Entries are selected before replay begins, so the failure tally counts only
	// the entries actually attempted.
	Filter EntryFilter

	// FailOnStatus counts a response of 400 or above as a failed entry, so that a
	// replay of a broken recording exits non-zero. By default any response the
	// server actually returned is a success, since a recorded 404 is often the
	// expected result.
	FailOnStatus bool

	// Logger receives diagnostics about skipped and failed entries. A nil
	// Logger discards them.
	Logger *slog.Logger

	// Progress receives one line per replayed entry. A nil Progress discards it.
	Progress io.Writer
}

RunOptions controls how Run replays a HAR file. The zero value replays in real time with cookies applied, TLS verified, and no output.

type TestResult

type TestResult struct {
	URL       string    `json:"url"`
	Status    int       `json:"status"` // 200, 500, etc.
	StartTime time.Time `json:"startTime"`
	EndTime   time.Time `json:"endTime"`
	Latency   int       `json:"latency"` // milliseconds
	// Duration is the full round trip, including receiving the response body.
	// Latency is the same measurement truncated to whole milliseconds, which is
	// too coarse for percentiles against a fast server.
	Duration time.Duration `json:"duration"`
	Method   string        `json:"method"`
	HARFile  string        `json:"harfile"`
}

TestResult contains results for an individual HTTP request.

type Timings

type Timings struct {
	// Time spent in a queue waiting for a network connection. Use -1 if the
	// timing does not apply to the current request.
	Blocked float64 `json:"blocked,omitempty"`
	// optional - DNS resolution time. The time required to resolve a host name.
	// Use -1 if the timing does not apply to the current request.
	DNS float64 `json:"dns,omitempty"`
	// optional - Time required to create the TCP connection. Use -1 if the timing
	// does not apply to the current request.
	Connect float64 `json:"connect,omitempty"`
	// Time required to send the HTTP request to the server.
	Send float64 `json:"send"`
	// Waiting for a response from the server.
	Wait float64 `json:"wait"`
	// Time required to read the entire response from the server (or cache).
	Receive float64 `json:"receive"`
	// optional (new in 1.2) - Time required for SSL/TLS negotiation. If this
	// field is defined then the time is also included in the connect field (to
	// ensure backward compatibility with HAR 1.1). Use -1 if the timing does not
	// apply to the current request.
	Ssl float64 `json:"ssl,omitempty"`
	// optional (new in 1.2) - A comment provided by the user or the application.
	Comment string `json:"comment,omitempty"`
}

Timings describes various phases within a request-response round trip. All times are specified in milliseconds.

Values are fractional: recorders routinely emit numbers such as 2.7129996047616007, which cannot be unmarshalled into an integer field.

Directories

Path Synopsis
cmd
hargo command
Command hargo is a command line tool for working with HTTP Archive (.har) files: validating them, dumping their contents, converting them to curl commands, replaying them, fetching the resources they reference, and driving load tests from them.
Command hargo is a command line tool for working with HTTP Archive (.har) files: validating them, dumping their contents, converting them to curl commands, replaying them, fetching the resources they reference, and driving load tests from them.

Jump to

Keyboard shortcuts

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