httpcost

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 5 Imported by: 0

README

Iris HTTP Cost Middleware

This middleware measures the resource usage (time, memory, CPU, and network bytes) of incoming requests or custom jobs, providing a unified “cost” metric. It can help you track performance and resource consumption across your Iris-powered applications.

Table of Contents

  1. Overview
  2. Installation
  3. Usage
      1. Quick Start
      1. Using Compute for Custom Jobs
  4. Configuration
  5. Where to Use httpcost.Metric
  6. Tips & Ideas

Overview

The httpcost middleware calculates how “expensive” a request or process is, in terms of:

  • Time duration (seconds)
  • Memory usage (RAM + Network, in MB)
  • CPU time (in seconds)

This allows you, as a developer, to log or bill resource usage in multi-tenant environments, monitor suspiciously long requests, or simply analyze performance bottlenecks in your application.

Installation

go get github.com/kataras/iris/v14@latest

Usage

1. Quick Start

Register the HTTP cost middleware to your Iris app:

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/context"

    "github.com/kataras/iris/v14/middleware/httpcost"
)

func main() {
    app := iris.New()

    // Get the final metric.
    app.Use(func(ctx iris.Context) {
        // Fire the next handler(s) first,
        // in this case the httpcost middleware itself and the main handler.
        ctx.Next()
        // Get the cost metric for this request.
        metric, ok := httpcost.Get(ctx) 
        if ok {
            // store the metric somewhere or log it...
        }
    })

    // Use the default cost options for measuring each incoming request.
    app.Use(httpcost.New(httpcost.DefaultOptions))

    // Handlers that do some work...
    app.Get("/", func(ctx *context.Context) {
        // Doing some slow or resource-consuming operation...
        ctx.WriteString("Hello World")
    })

    // Start the server.
    app.Listen(":8080")
}

httpcost.Get(ctx) provides the final Metric, containing time, memory, CPU usage, and cost data.

Now each request’s cost is measured and stored in the request context. You can retrieve it in subsequent handlers to log or display the results.

2. Using Compute for Custom Jobs

To measure the cost of any custom Go function:

import "github.com/kataras/iris/v14/middleware/httpcost"

// Suppose you have a custom job to benchmark:
func myLongRunningJob() {
    // ...
}

func measureMyJob() {
    totalCost := httpcost.Compute(myLongRunningJob)
    println("Cost of my job:", totalCost)
}

Under the hood, Compute uses an internal Computer which starts tracking resource usage, runs your function, then stops and returns the total cost.

Configuration

The Options struct defines how costs are calculated:

type Options struct {
    CostPerSecond float64 // e.g. 0.01
    CostPerMB     float64 // e.g. 0.001
    CostPerCPU    float64 // e.g. 0.02
}

Any of these set to 0 disable that resource dimension for the calculation. You can create your own Options or use DefaultOptions:

opts := httpcost.Options{
    CostPerSecond: 0.02, // charge more per second
    CostPerMB:     0.0,  // ignore memory usage
    CostPerCPU:    0.02,
}
app.Use(httpcost.New(opts))

Where to Use httpcost.Metric

The httpcost.Metric struct is especially useful in:

  1. Analytics Dashboards: Store the metric in a database to visualize how resources are spent over time or per endpoint.
  2. Billing: If you host user-generated code or third-party logic, you can use Metric.Cost as the basis for usage-based billing.
  3. Performance Monitoring: Track CPU or memory outliers to identify poorly optimized endpoints.
  4. Resource Limits: Automatically detect large usage, e.g. suspicious or repeated resource-heavy requests, and take actions (block, throttle, or analyze further).

Tips & Ideas

  • Combine with Access Logs: Use “httpcost.Metric” alongside the AccessLog middleware to produce more detailed performance logs.
  • Alerting: If the cost passes a certain threshold, send an alert to your monitoring system.
  • Per-request Pricing: Combine the cost with user-specific factors to compute partial usage-based pricing.
  • Limit High Resource Use: If you detect unusual spikes in CPU or memory usage, consider adding concurrency limits or queueing strategies to protect critical workloads.

Happy coding with Iris and the httpcost middleware!

Documentation

Overview

Package httpcost measures the CPU, memory and time cost of serving a request. Its entry point is New(Options), which returns a Handler that stores a *Metric on the Context; read it back with Get.

Index

Constants

This section is empty.

Variables

View Source
var DefaultOptions = Options{
	CostPerSecond: 0.01,
	CostPerMB:     0.001,
	CostPerCPU:    0.02,
}

DefaultOptions contains the default cost configuration for the package:

  • CostPerSecond: 0.01
  • CostPerMB: 0.001
  • CostPerCPU: 0.02

Functions

func Compute

func Compute(job func()) float64

Compute calculates and returns the cost of the given job.

It uses the DefaultOptions to initialize a new Computer, starts a running process measurement, executes the provided job function, and then stops the measurement. It returns the total cost as a float64.

func New

func New(opts Options) context.Handler

New returns an Iris Handler that measures request cost using the provided Options. It starts a RunningProcess before ctx.Next() and stops it afterward, storing the resulting Metric into the request context. It should be registered before the handlers you want to measure.

Usage:

app.Use(httpcost.New(httpcost.DefaultOptions))

Types

type Computer

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

Computer is responsible for calculating the cost of a job.

It holds the Options and uses them to start and stop RunningProcess measurements.

func NewComputer

func NewComputer(opts Options) *Computer

NewComputer returns a new Computer instance, or panics if all Options are disabled (i.e. zero cost metrics).

Usage:

computer := httpcost.NewComputer(httpcost.DefaultOptions)

func (*Computer) Start

func (c *Computer) Start() *RunningProcess

Start initializes a new RunningProcess and records the current time, CPU usage, and memory usage if the respective cost metrics are enabled.

type Metric

type Metric struct {
	StartTime   types.ISO8601 `pg:"type=timestamp" json:"start_time"`
	Duration    time.Duration `pg:"type=interval" json:"duration"`
	MemoryUsed  uint64        `pg:"type=int8" json:"memory_used"`  // bytes.
	NetworkUsed uint64        `pg:"type=int8" json:"network_used"` // bytes.
	CpuTime     float64       `pg:"type=decimal" json:"cpu_time"`  // seconds.
	Cost        float64       `pg:"type=decimal" json:"cost"`
}

Metric holds the final measurement data and total cost.

func Get

func Get(ctx *context.Context) (*Metric, bool)

Get retrieves the cost Metric from the provided context. It returns the Metric and a boolean indicating if it was found.

type Options

type Options struct {
	// The cost per second of time to execute the job.
	// Zero disables the time duration cost. DefaultOptions sets 0.01.
	CostPerSecond float64 `json:"cost_per_second" yaml:"CostPerSecond" toml:"CostPerSecond"`
	// The cost per MB of memory used (RAM (and Network)).
	// Zero disables the memory cost. DefaultOptions sets 0.001.
	CostPerMB float64 `json:"cost_per_mb" yaml:"CostPerMB" toml:"CostPerMB"`
	// The cost per second of CPU time.
	// Zero disables the CPU time cost. DefaultOptions sets 0.02.
	CostPerCPU float64 `json:"cost_per_cpu" yaml:"CostPerCPU" toml:"CostPerCPU"`
}

Options contains the cost configuration for time, memory, CPU, and network usage.

CostPerSecond sets the cost per elapsed second. CostPerMB sets the cost per MB of used (RAM/Network) memory. CostPerCPU sets the cost per CPU-second.

A zero field disables that cost; there are no per-field defaults. DefaultOptions carries the usual values (0.01, 0.001 and 0.02). At least one cost must be above zero, or New and NewComputer panic.

type RunningProcess

type RunningProcess struct {
	Options *Options

	StartTime        time.Time // timestamp of the beginning.
	StartCpuUsage    float64   // seconds to perform.
	StartMemoryUsage uint64    // bytes.
}

RunningProcess represents an ongoing measurement of time, CPU, and memory usage.

func (*RunningProcess) Stop

func (proc *RunningProcess) Stop(netBytes int) *Metric

Stop finishes the measurement and calculates the cost.

netBytes is the total number of bytes written to the network.

Jump to

Keyboard shortcuts

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