client

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 10 Imported by: 0

Documentation

Overview

Package client provides a Go SDK for the powhttp Data API.

The powhttp Data API provides a RESTful HTTP interface to programmatically access session data, entries, and connection details from powhttp. This SDK enables building custom integrations, exporting data to external tools, or automating workflows based on captured network traffic.

Quick Start

Create a client and list sessions:

c := client.New()
sessions, err := c.ListSessions(ctx)

Use custom configuration:

c := client.New(
    client.WithBaseURL("http://localhost:8080"),
    client.WithHTTPClient(customHTTPClient),
)

The "active" Identifier

Many methods accept "active" as a special identifier to reference the currently active session or entry in the powhttp interface:

// Get the currently active session
session, err := c.GetSession(ctx, "active")

// Get the currently active entry in the active session
entry, err := c.GetEntry(ctx, "active", "active")

Entry Filtering

The ListEntries method supports filtering by selection state, bookmarks, and highlight colors:

entries, err := c.ListEntries(ctx, "active", &client.ListEntriesOptions{
    Selected:    true,
    Bookmarked:  true,
    Highlighted: []string{client.HighlightRed, client.HighlightYellow},
})

Working with Bodies

Request and response bodies are base64-encoded. Use DecodeBody to decode them:

body, err := client.DecodeBody(entry.Response.Body)

Working with Headers

Headers are returned as a slice of key-value pairs. The Headers type provides helper methods for common operations:

contentType := entry.Response.Headers.Get("Content-Type")
cookies := entry.Response.Headers.Values("Set-Cookie")

TLS and HTTP/2 Details

For entries using TLS or HTTP/2, you can retrieve detailed connection information. The connection ID is found in the entry's TLS or HTTP2 fields:

// Get TLS handshake events
if entry.TLS.ConnectionID != nil {
    events, err := c.GetTLSConnection(ctx, *entry.TLS.ConnectionID)
}

// Get HTTP/2 stream details
if entry.HTTP2 != nil {
    frames, err := c.GetHTTP2Stream(ctx, entry.HTTP2.ConnectionID, entry.HTTP2.StreamID)
}

TLS events and HTTP/2 frames are returned as json.RawMessage slices since their schemas vary by event/frame type.

Index

Constants

View Source
const (
	HighlightRed           = "red"
	HighlightGreen         = "green"
	HighlightBlue          = "blue"
	HighlightYellow        = "yellow"
	HighlightGray          = "gray"
	HighlightOrange        = "orange"
	HighlightPink          = "pink"
	HighlightPurple        = "purple"
	HighlightStrikethrough = "strikethrough"
)

Highlight colors for ListEntriesOptions.Highlighted

View Source
const (
	WSMessageText    = "text"
	WSMessageBinary  = "binary"
	WSMessageClose   = "close"
	WSMessagePing    = "ping"
	WSMessagePong    = "pong"
	WSMessageUnknown = "unknown"
)

WebSocket message types

View Source
const (
	WSSideClient = "client"
	WSSideServer = "server"
)

WebSocket sides

View Source
const (
	TransactionRequest     = "request"
	TransactionPushPromise = "push_promise"
)

Transaction types

View Source
const (
	TLSSideClient = "client"
	TLSSideServer = "server"
)

TLS event sides

View Source
const (
	TLSMsgHandshake        = "handshake"
	TLSMsgChangeCipherSpec = "change_cipher_spec"
)

TLS message types

View Source
const (
	TLSHandshakeClientHello         = "client_hello"
	TLSHandshakeServerHello         = "server_hello"
	TLSHandshakeEncryptedExtensions = "encrypted_extensions"
	TLSHandshakeCertificate         = "certificate"
	TLSHandshakeCertificateVerify   = "certificate_verify"
	TLSHandshakeFinished            = "finished"
)

TLS handshake message types

View Source
const DefaultBaseURL = "http://localhost:7777"

DefaultBaseURL is the default base URL for the powhttp Data API.

Variables

This section is empty.

Functions

func DecodeBody

func DecodeBody(encoded *string) ([]byte, error)

DecodeBody decodes a base64-encoded body. Returns nil if the input is nil.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
}

APIError represents an error response from the powhttp API.

func (*APIError) Error

func (e *APIError) Error() string

type Client

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

Client is a powhttp Data API client.

func New

func New(opts ...Option) *Client

New creates a new powhttp API client.

func (*Client) GetEntry

func (c *Client) GetEntry(ctx context.Context, sessionID, entryID string) (*SessionEntry, error)

GetEntry retrieves a specific entry within a session. Use "active" as sessionID or entryID to reference currently active resources.

func (*Client) GetHTTP2Stream

func (c *Client) GetHTTP2Stream(ctx context.Context, connectionID string, streamID int) ([]json.RawMessage, error)

GetHTTP2Stream retrieves frame-level details for a specific HTTP/2 stream. Returns raw JSON events since the schema varies by frame type.

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, sessionID string) (*Session, error)

GetSession retrieves a specific session by ID. Use "active" as the sessionID to get the currently active session.

func (*Client) GetSessionBookmarks

func (c *Client) GetSessionBookmarks(ctx context.Context, sessionID string) ([]string, error)

GetSessionBookmarks retrieves bookmarked entry IDs for a session. Use "active" as the sessionID to reference the currently active session.

func (*Client) GetTLSConnection

func (c *Client) GetTLSConnection(ctx context.Context, connectionID string) ([]TLSEvent, error)

GetTLSConnection retrieves TLS handshake events for a connection. The connectionID can be found in the TLS.ConnectionID field of an entry. Returns a slice of TLSEvent containing the handshake messages.

func (*Client) GetWebSocketMessages

func (c *Client) GetWebSocketMessages(ctx context.Context, sessionID, entryID string) ([]WebSocketMessage, error)

GetWebSocketMessages retrieves all WebSocket messages for an entry. Returns an error if the entry is not a WebSocket connection. Use "active" as sessionID or entryID to reference currently active resources.

func (*Client) ListEntries

func (c *Client) ListEntries(ctx context.Context, sessionID string, opts *ListEntriesOptions) ([]SessionEntry, error)

ListEntries retrieves all entries within a session. Use "active" as the sessionID to reference the currently active session.

func (*Client) ListHTTP2StreamIDs

func (c *Client) ListHTTP2StreamIDs(ctx context.Context, connectionID string) ([]int, error)

ListHTTP2StreamIDs retrieves all stream IDs for an HTTP/2 connection. The connectionID can be found in the HTTP2.ConnectionID field of an entry.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) ([]Session, error)

ListSessions retrieves all sessions currently loaded in powhttp.

type HTTP2Info

type HTTP2Info struct {
	ConnectionID string `json:"connectionId"`
	StreamID     int    `json:"streamId"`
}

HTTP2Info contains HTTP/2 connection information for an entry.

type Headers

type Headers [][]string

Headers is a slice of header key-value pairs.

func (Headers) Get

func (h Headers) Get(name string) string

Get returns the first value for the given header name (case-insensitive). Returns an empty string if the header is not found.

func (Headers) Values

func (h Headers) Values(name string) []string

Values returns all values for the given header name (case-insensitive).

type JA3Fingerprint

type JA3Fingerprint struct {
	String string `json:"string"`
	Hash   string `json:"hash"`
}

JA3Fingerprint represents a JA3 TLS fingerprint.

type JA4Fingerprint

type JA4Fingerprint struct {
	Raw    string `json:"raw"`
	Hashed string `json:"hashed"`
}

JA4Fingerprint represents a JA4 TLS fingerprint.

type ListEntriesOptions

type ListEntriesOptions struct {
	// Selected filters to only return entries that are currently selected in the powhttp interface.
	Selected bool
	// Bookmarked filters to only return entries that are currently bookmarked.
	Bookmarked bool
	// Highlighted filters entries by their highlight state.
	// Use constants like HighlightRed, HighlightGreen, HighlightStrikethrough, etc.
	Highlighted []string
}

ListEntriesOptions contains optional filters for listing entries.

type Option

type Option func(*Client)

Option is a functional option for configuring the Client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets a custom base URL for the API.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets a custom HTTP client.

type ProcessInfo

type ProcessInfo struct {
	PID  int     `json:"pid"`
	Name *string `json:"name"`
}

ProcessInfo contains information about the process that made the request.

type Request

type Request struct {
	Method      *string `json:"method"`
	Path        *string `json:"path"`
	HTTPVersion *string `json:"httpVersion"`
	Headers     Headers `json:"headers"`
	Body        *string `json:"body"` // Base64-encoded
}

Request represents an HTTP request.

type Response

type Response struct {
	HTTPVersion *string `json:"httpVersion"`
	StatusCode  *int    `json:"statusCode"`
	StatusText  *string `json:"statusText"`
	Headers     Headers `json:"headers"`
	Body        *string `json:"body"` // Base64-encoded
}

Response represents an HTTP response.

type Session

type Session struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	EntryIDs []string `json:"entryIds"`
}

Session represents a powhttp session containing captured network traffic.

type SessionEntry

type SessionEntry struct {
	ID              string         `json:"id"`
	URL             string         `json:"url"`
	ClientAddr      *SocketAddress `json:"clientAddr"`
	RemoteAddr      *SocketAddress `json:"remoteAddr"`
	HTTPVersion     string         `json:"httpVersion"`
	TransactionType string         `json:"transactionType"` // "request" or "push_promise"
	Request         Request        `json:"request"`
	Response        *Response      `json:"response"`
	IsWebSocket     bool           `json:"isWebSocket"`
	TLS             TLSInfo        `json:"tls"`
	HTTP2           *HTTP2Info     `json:"http2"`
	Timings         Timings        `json:"timings"`
	Process         *ProcessInfo   `json:"process"`
}

SessionEntry represents an individual HTTP transaction captured within a session.

type SocketAddress

type SocketAddress struct {
	IP   string `json:"ip"`
	Port *int   `json:"port"`
}

SocketAddress represents an IP address and optional port.

type TLSCertificate

type TLSCertificate struct {
	CertificateRequestContext string                `json:"certificate_request_context"`
	CertificateList           []TLSCertificateEntry `json:"certificate_list"`
}

TLSCertificate represents a TLS Certificate message.

type TLSCertificateEntry

type TLSCertificateEntry struct {
	CertData   string `json:"cert_data"` // Hex-encoded DER certificate
	Extensions string `json:"extensions"`
}

TLSCertificateEntry represents a single certificate in a certificate chain.

type TLSCertificateVerify

type TLSCertificateVerify struct {
	Algorithm TLSNamedValue `json:"algorithm"`
	Signature string        `json:"signature"` // Hex-encoded
}

TLSCertificateVerify represents a TLS CertificateVerify message.

type TLSChangeCipherSpec

type TLSChangeCipherSpec struct {
	Data string `json:"data"` // Hex-encoded
}

TLSChangeCipherSpec represents a TLS ChangeCipherSpec message.

type TLSClientHello

type TLSClientHello struct {
	Version            TLSNamedValue   `json:"version"`
	Random             string          `json:"random"`
	SessionID          string          `json:"session_id"`
	CipherSuites       []TLSNamedValue `json:"cipher_suites"`
	CompressionMethods []TLSNamedValue `json:"compression_methods"`
	Extensions         json.RawMessage `json:"extensions"` // Complex, varies by extension type
}

TLSClientHello represents a TLS ClientHello message.

type TLSEncryptedExtensions

type TLSEncryptedExtensions struct {
	Extensions json.RawMessage `json:"extensions"`
}

TLSEncryptedExtensions represents encrypted extensions sent by the server.

type TLSEvent

type TLSEvent struct {
	Side string            `json:"side"` // "client" or "server"
	Msg  TLSMessageContent `json:"msg"`
}

TLSEvent represents a single TLS event in the connection handshake.

type TLSExtension

type TLSExtension struct {
	Value int             `json:"value"`
	Name  string          `json:"name"`
	Data  json.RawMessage `json:"-"` // Remaining fields vary by extension type
}

TLSExtension represents a TLS extension with variable content.

type TLSFinished

type TLSFinished struct {
	VerifyData string `json:"verify_data"` // Hex-encoded
}

TLSFinished represents a TLS Finished message.

type TLSHandshakeContent

type TLSHandshakeContent struct {
	Type                string
	ClientHello         *TLSClientHello
	ServerHello         *TLSServerHello
	EncryptedExtensions *TLSEncryptedExtensions
	Certificate         *TLSCertificate
	CertificateVerify   *TLSCertificateVerify
	Finished            *TLSFinished
}

TLSHandshakeContent wraps the various handshake message types. Only one field will be populated based on Type.

func (*TLSHandshakeContent) UnmarshalJSON

func (h *TLSHandshakeContent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for TLSHandshakeContent.

type TLSInfo

type TLSInfo struct {
	ConnectionID *string         `json:"connectionId"`
	TLSVersion   *int            `json:"tlsVersion"`
	CipherSuite  *int            `json:"cipherSuite"`
	JA3          *JA3Fingerprint `json:"ja3"`
	JA4          *JA4Fingerprint `json:"ja4"`
}

TLSInfo contains TLS connection information for an entry.

type TLSMessageContent

type TLSMessageContent struct {
	Type             string
	Handshake        *TLSHandshakeContent
	ChangeCipherSpec *TLSChangeCipherSpec
}

TLSMessageContent wraps handshake or change_cipher_spec content. Check Type to determine which field is populated.

func (*TLSMessageContent) UnmarshalJSON

func (m *TLSMessageContent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling for TLSMessageContent.

type TLSNamedValue

type TLSNamedValue struct {
	Value int    `json:"value"`
	Name  string `json:"name"`
}

TLSNamedValue represents a value with its numeric code and human-readable name.

type TLSServerHello

type TLSServerHello struct {
	Version           TLSNamedValue   `json:"version"`
	Random            string          `json:"random"`
	SessionID         string          `json:"session_id"`
	CipherSuite       TLSNamedValue   `json:"cipher_suite"`
	CompressionMethod TLSNamedValue   `json:"compression_method"`
	Extensions        json.RawMessage `json:"extensions"`
}

TLSServerHello represents a TLS ServerHello message.

type Timings

type Timings struct {
	StartedAt int64  `json:"startedAt"` // Unix timestamp in milliseconds
	Blocked   *int64 `json:"blocked"`
	DNS       *int64 `json:"dns"`
	Connect   *int64 `json:"connect"`
	Send      *int64 `json:"send"`
	Wait      *int64 `json:"wait"`
	Receive   *int64 `json:"receive"`
	SSL       *int64 `json:"ssl"`
}

Timings contains timing information for an HTTP transaction.

type WebSocketContent

type WebSocketContent struct {
	Type   string `json:"type"`             // "text", "binary", "close", "ping", "pong", "unknown"
	Text   string `json:"text,omitempty"`   // when Type == "text"
	Data   string `json:"data,omitempty"`   // when Type == "binary"/"ping"/"pong"/"unknown" (base64)
	Code   int    `json:"code,omitempty"`   // when Type == "close"
	Reason string `json:"reason,omitempty"` // when Type == "close" (base64)
}

WebSocketContent represents the content of a WebSocket message. Check the Type field to determine which content fields are populated.

type WebSocketMessage

type WebSocketMessage struct {
	Side      string           `json:"side"` // "client" or "server"
	StartedAt *int64           `json:"startedAt"`
	EndedAt   *int64           `json:"endedAt"`
	Content   WebSocketContent `json:"content"`
}

WebSocketMessage represents a single WebSocket message.

Jump to

Keyboard shortcuts

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