go_har

package module
v0.0.0-...-cb0c950 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2024 License: MIT Imports: 25 Imported by: 0

README

go-har

GoDoc Go Report Card

golang parses HAR files

What is Har?

https://w3c.github.io/web-performance/specs/HAR/Overview.html

https://toolbox.googleapps.com/apps/har_analyzer/

Feature

  • supports standard HAR-1.2 content parsing
  • replay HTTP request based on har content stub content
  • supports HTTP synchronous requests and asynchronous concurrent requests
  • .har file import and export
  • can be embedded in HTTP services to present data
  • build HAR based on http.Request and http.Response

Use restriction

  • golang version >= 1.21

Example

package main

import (
	"context"
	"errors"
	"fmt
	"io"
	"log"
	"net/http"
	"time"

	har "github.com/chaunsin/go-har"
)

func Example() {
	var path = "./testdata/zh.wikipedia.org.har"
	// parse har file
	h, err := Parse(path, WithCookie(true))
	if err != nil {
		log.Fatalf("Parse: %s", err)
	}
	har := h.Export().Log
	fmt.Printf("version: %s create: %+v entries: %v\n", har.Version, har.Creator, h.EntryTotal())

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()

	// construct request filter
	filter := []RequestOption{
		WithRequestUrlIs("https://zh.wikipedia.org/wiki/.har"),
		WithRequestMethod("GET"),
		// add another filter
	}

	// concurrent execution http request
	receipt, err := h.SyncExecute(ctx, filter...)
	if err != nil {
		log.Fatalf("SyncExecute: %s", err)
	}
	for r := range receipt {
		switch {
		case errors.Is(r.err, context.DeadlineExceeded):
			log.Printf("%s request is timeout!", r.Entry.Request.URL)
			continue
		case r.err != nil:
			log.Printf("%s request failed: %s\n", r.Entry.Request.URL, r.Error())
			continue
		}

		// Anonymous functions avoid body resource leakage
		func() {
			defer r.Response.Body.Close()
			_, err := io.ReadAll(r.Response.Body)
			if err != nil {
				log.Fatalf("readall err:%s", err)
				return
			}
			fmt.Printf("url: %s status: %s\n", r.Entry.Request.URL, r.Response.Status)
		}()
	}

	// add a new golang standard http request
	uniqueId := "1"
	request, err := http.NewRequest(http.MethodGet, "https://www.baidu.com", nil)
	if err != nil {
		panic(err)
	}
	if err := h.AddRequest(uniqueId, request); err != nil {
		// err maybe unique id is repeated
		log.Fatalf("add request failed: %s", err)
	}

	// exclude other requests, ready for execution https://www.baidu.com
	filter = []RequestOption{WithRequestUrlIs("https://www.baidu.com")}

	// sequential execution http request
	execReceipt, err := h.Execute(context.TODO(), filter...)
	if err != nil {
		log.Fatalf("Execute: %s", err)
	}
	for _, r := range execReceipt {
		if r.Error() != nil {
			log.Printf("%s request failed: %s\n", r.Entry.Request.URL, r.Error())
			continue
		}
		func() {
			defer r.Response.Body.Close()
			// read body do something's
			_, err := io.ReadAll(r.Response.Body)
			if err != nil {
				log.Fatalf("readall err:%s", err)
				return
			}

			// fill in response to current entry.Response
			if err := r.FillInResponse(); err != nil {
				log.Printf("FillInResponse: %e", err)
			}

			fmt.Printf("url: %s status: %s\n", r.Entry.Request.URL, r.Response.Status)
		}()
	}

	// Writes the contents of the internal har json object to IO
	if err := h.Write(io.Discard); err != nil {
		log.Fatalf("write err:%s", err)
	}

	// clean har
	h.Reset()
	fmt.Println("entries:", h.EntryTotal())

	// Output:
	// version: 1.2 create: &{Name:WebInspector Version:537.36 Comment:} entries: 3
	// url: https://zh.wikipedia.org/wiki/.har status: 200 OK
	// url: https://www.baidu.com status: 200 OK
	// entries: 0
}

Please refer to example_test.go

Documentation

Overview

Example
var path = "./testdata/zh.wikipedia.org.har"
// parse har file
h, err := Parse(path, WithCookie(true))
if err != nil {
	log.Fatalf("Parse: %s", err)
}
har := h.Export().Log
fmt.Printf("version: %s create: %+v entries: %v\n", har.Version, har.Creator, h.EntryTotal())

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()

// construct request filter
filter := []RequestOption{
	WithRequestUrlIs("https://zh.wikipedia.org/wiki/.har"),
	// WithRequestMethod("GET"),
	// add another filter
}

// concurrent execution http request
receipt, err := h.SyncExecute(ctx, filter...)
if err != nil {
	log.Fatalf("SyncExecute: %s", err)
}
for r := range receipt {
	switch {
	case errors.Is(r.err, context.DeadlineExceeded):
		log.Printf("%s request is timeout!", r.Entry.Request.URL)
		continue
	case r.err != nil:
		log.Printf("%s request failed: %s\n", r.Entry.Request.URL, r.Error())
		continue
	}

	// Anonymous functions avoid body resource leakage
	func() {
		defer r.Response.Body.Close()
		_, err := io.ReadAll(r.Response.Body)
		if err != nil {
			log.Fatalf("readall err:%s", err)
			return
		}
		fmt.Printf("url: %s status: %s\n", r.Entry.Request.URL, r.Response.Status)
	}()
}

// add a new golang standard http request
uniqueId := "1"
request, err := http.NewRequest(http.MethodGet, "https://www.baidu.com", nil)
if err != nil {
	panic(err)
}
if err := h.AddRequest(uniqueId, request); err != nil {
	// err maybe unique id is repeated
	log.Fatalf("add request failed: %s", err)
}

// exclude other requests, ready for execution https://www.baidu.com
filter = []RequestOption{WithRequestUrlIs("https://www.baidu.com")}

// sequential execution http request
execReceipt, err := h.Execute(context.TODO(), filter...)
if err != nil {
	log.Fatalf("Execute: %s", err)
}
for _, r := range execReceipt {
	if r.Error() != nil {
		log.Printf("%s request failed: %s\n", r.Entry.Request.URL, r.Error())
		continue
	}
	func() {
		defer r.Response.Body.Close()
		// read body do something's
		_, err := io.ReadAll(r.Response.Body)
		if err != nil {
			log.Fatalf("readall err:%s", err)
			return
		}

		// fill in response to current entry.Response
		if err := r.FillInResponse(); err != nil {
			log.Printf("FillInResponse: %e", err)
		}

		fmt.Printf("url: %s status: %s\n", r.Entry.Request.URL, r.Response.Status)
	}()
}

// Writes the contents of the internal har json object to IO
if err := h.Write(io.Discard); err != nil {
	log.Fatalf("write err:%s", err)
}

// clean har
h.Reset()
fmt.Println("entries:", h.EntryTotal())
Output:

version: 1.2 create: &{Name:WebInspector Version:537.36 Comment:} entries: 3
url: https://zh.wikipedia.org/wiki/.har status: 200 OK
url: https://www.baidu.com status: 200 OK
entries: 0

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func EntryToRequest

func EntryToRequest(e *Entry, withCookie bool) (*http.Request, error)

EntryToRequest .

func ParseISO8601

func ParseISO8601(str string) (time.Time, error)

ParseISO8601 parse ISO8601 standard format time

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,omitempty"`
}

Browser This object contains information about the browser that created the log and contains the following name/value pairs:

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 int64 `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 int64 `json:"size"`
	// [optional] Number of bytes saved. Leave out this field if the information
	// is not available.
	Compression int64 `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 an encoded (e.g. "base64") representation of
	// the response body. Leave out this field if the information is not
	// available.
	Text []byte `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), then 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"`
}

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

func (*Content) MarshalJSON

func (c *Content) MarshalJSON() ([]byte, error)

MarshalJSON marshals the byte slice into json after encoding based on c.Encoding.

func (*Content) UnmarshalJSON

func (c *Content) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal the bytes slice into Content.

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 This object contains information about the log creator application and contains the following name/value pairs:

type EntityHandler

type EntityHandler func(e *Entry) bool

type Entry

type Entry struct {
	// [string, unique, optional] Reference to the parent page.
	// Leave out this field if the application does not support grouping by pages.
	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 timing 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 a request/response round trip.
	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 a 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 This object represents an array with all exported HTTP requests. Sorting entries by startedDateTime (starting from the oldest) is the 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)

type Handler

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

func NewHandler

func NewHandler(har *Har, opts ...Option) (*Handler, error)

func NewReader

func NewReader(r io.Reader, opts ...Option) (*Handler, error)

func Parse

func Parse(path string, opts ...Option) (*Handler, error)
Example
path := "./testdata/zh.wikipedia.org.har"
h, err := Parse(path)
if err != nil {
	panic(err)
}
fmt.Printf("%+v\n", h.Export())

file, err := os.Open(path)
if err != nil {
	panic(err)
}
defer file.Close()
h, err = NewReader(file)
if err != nil {
	panic(err)
}
fmt.Printf("%+v\n", h.Export())

// user default har
h, err = NewHandler(nil)
if err != nil {
	panic(err)
}
fmt.Printf("%+v\n", h.Export())
Output:

&{Log:{Version:1.2 Creator:0xc00010af90 Browser:<nil> Pages:[] Entries:[0xc00015a080] Comment:}}
&{Log:{Version:1.2 Creator:0xc0001ae5d0 Browser:<nil> Pages:[] Entries:[0xc00015a180] Comment:}}
&{Log:{Version:1.2 Creator:0xc0001aecc0 Browser:<nil> Pages:[] Entries:[] Comment:}}

func (*Handler) AddRequest

func (h *Handler) AddRequest(id string, r *http.Request) error

AddRequest Add an http.Request to Har

func (*Handler) AddResponse

func (h *Handler) AddResponse(id string, resp *http.Response) error

AddResponse Add an http.Response to Har if the data exists, overwrite it, otherwise, no operation is performed

func (*Handler) EntryTotal

func (h *Handler) EntryTotal() int64

EntryTotal Returns the total number of entries

func (*Handler) Execute

func (h *Handler) Execute(ctx context.Context, filter ...RequestOption) ([]Receipt, error)

Execute sequential synchronous http execution

func (*Handler) Export

func (h *Handler) Export() *Har

Export Har structure data Note: The exported data is a copy object, and modifying the Har does not affect the original value

func (*Handler) Reset

func (h *Handler) Reset()

Reset the Har structure data

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Handler) SyncExecute

func (h *Handler) SyncExecute(ctx context.Context, filter ...RequestOption) (<-chan Receipt, error)

SyncExecute concurrent execution http request. Note: The order of execution is not guaranteed

func (*Handler) Write

func (h *Handler) Write(w io.Writer) error

Write writes the Har data to the writer

type Har

type Har struct {
	Log *Log `json:"log"`
}

Har HTTP Archive (HAR) format https://w3c.github.io/web-performance/specs/HAR/Overview.html This specification defines an archival format for HTTP transactions that can be used by a web browser to export detailed performance data about web pages it loads.

func (*Har) Validate

func (h *Har) Validate() error

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,omitempty"`
	// [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.
	Comment string `json:"comment,omitempty"`
}

Log This object represents the root of the exported data. This object MUST be present and its name MUST be "log". The object contains the following name/value pairs:

type Logger

type Logger interface {
	Debug(format string, args ...any)
	Info(format string, args ...any)
	Warn(format string, args ...any)
	Error(format string, args ...any)
}

func NewLogger

func NewLogger(format string, level string, writer ...io.Writer) Logger

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 Option

type Option func(h *Handler)

Option represents the optional function

func WithComment

func WithComment(str string) Option

WithComment .

func WithCookie

func WithCookie(c bool) Option

WithCookie whether http requests carry cookies

func WithLogger

func WithLogger(l Logger) Option

WithLogger Register a logger object interface

func WithRequestBody

func WithRequestBody(enabled bool) Option

WithRequestBody returns an option that configures request post data logging.

func WithRequestBodyByContentTypes

func WithRequestBodyByContentTypes(cts ...string) Option

WithRequestBodyByContentTypes returns an option that logs request bodies based on opting in to the Content-Type of the request.

func WithRequestConcurrency

func WithRequestConcurrency(num uint64) Option

WithRequestConcurrency Number of concurrent http requests allowed. 0 indicates no limit.

func WithResponseBody

func WithResponseBody(enabled bool) Option

WithResponseBody returns an option that configures response body logging.

func WithResponseBodyByContentTypes

func WithResponseBodyByContentTypes(cts ...string) Option

WithResponseBodyByContentTypes returns an option that logs response bodies based on opting in to the Content-Type of the response.

func WithSkipRequestBodyForContentTypes

func WithSkipRequestBodyForContentTypes(cts ...string) Option

WithSkipRequestBodyForContentTypes returns an option that logs request bodies based on opting out of the Content-Type of the request.

func WithSkipResponseBodyForContentTypes

func WithSkipResponseBodyForContentTypes(cts ...string) Option

WithSkipResponseBodyForContentTypes returns an option that logs response bodies based on opting out of the Content-Type of the response.

func WithTransport

func WithTransport(t http.RoundTripper) Option

WithTransport set http.RoundTripper

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 a 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 There is one <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 don't have a parent page.

type PageTimings

type PageTimings struct {
	// Content of the page loaded. Number of milliseconds since a page load started
	// (page.startedDateTime). Use -1 if the timing does not apply to the current
	// request.
	// Depending 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 a 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 time info is not available, the appropriate field is set to -1.

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).

func (*PostData) MarshalJSON

func (p *PostData) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON representation of binary PostData.

func (*PostData) UnmarshalJSON

func (p *PostData) UnmarshalJSON(data []byte) error

UnmarshalJSON populates PostData based on the []byte representation of the binary PostData.

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 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 Receipt

type Receipt struct {
	Entry    *Entry
	Response *http.Response
	// contains filtered or unexported fields
}

func (*Receipt) Body

func (r *Receipt) Body() []byte

func (*Receipt) Error

func (r *Receipt) Error() error

func (*Receipt) FillInResponse

func (r *Receipt) FillInResponse(withBody ...bool) error

FillInResponse TODO: 读取body会造成内存过大考虑优化

type ReqHandler

type ReqHandler func(req *http.Request) bool

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 info.
	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.
	HeaderSize int64 `json:"headerSize"`
	// Size of the request body (POST data payload) in bytes. Set to -1 if the
	// info is not available.
	BodySize int64 `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.

func NewRequest

func NewRequest(req *http.Request, withBody bool) (*Request, error)

NewRequest .

type RequestOption

type RequestOption func(ctx *Handler, e *Entry) bool

RequestOption SyncExecute() or Execute() represents the optional function TODO: The current condition is a OR condition, which needs to be changed into an AND policy

func WithRequestHandler

func WithRequestHandler(handler EntityHandler) RequestOption

WithRequestHandler .

func WithRequestHostIs

func WithRequestHostIs(hosts ...string) RequestOption

WithRequestHostIs .

func WithRequestHostRegexp

func WithRequestHostRegexp(regexps ...*regexp.Regexp) RequestOption

WithRequestHostRegexp .

func WithRequestMethod

func WithRequestMethod(methods ...string) RequestOption

WithRequestMethod .

func WithRequestUrlIs

func WithRequestUrlIs(urls ...string) RequestOption

WithRequestUrlIs .

func WithRequestUrlPrefix

func WithRequestUrlPrefix(prefix string) RequestOption

WithRequestUrlPrefix .

func WithRequestUrlRegexp

func WithRequestUrlRegexp(regexps *regexp.Regexp) RequestOption

WithRequestUrlRegexp .

func WithSkipRequestMethod

func WithSkipRequestMethod(methods ...string) RequestOption

WithSkipRequestMethod .

type RespHandler

type RespHandler func(req *http.Response) bool

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 int64 `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 int64 `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. The total response size received can be computed as follows (if both values are available): var totalSize = entry.response.headersSize + entry.response.bodySize;

func NewResponse

func NewResponse(res *http.Response, withBody bool) (*Response, error)

NewResponse .

type Time

type Time time.Time

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

func (*Time) MarshalText

func (t *Time) MarshalText() ([]byte, error)

func (*Time) String

func (t *Time) String() string

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(text []byte) (err error)

func (*Time) UnmarshalText

func (t *Time) UnmarshalText(text []byte) (err error)

type Timings

type Timings struct {
	// [optional] 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 TCP connection. Use -1 if the timing
	// does not apply to the current request.
	Connect float64 `json:"connect,omitempty"`
	// Time required to send an 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 connected 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 describe various phases within a request-response round trip. All times are specified in milliseconds.

Directories

Path Synopsis
Package messageview provides no-op snapshots for HTTP requests and responses.
Package messageview provides no-op snapshots for HTTP requests and responses.

Jump to

Keyboard shortcuts

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