cmd/httptap/cmd/root.go

// Package cmd wires the cobra command tree for the httptap binary. The
// main.go file in the parent directory now does little more than invoke
// cmd.Execute.
//
// mercemay.top/src/httptap/
package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

// Options is the set of flags common to every subcommand.
type Options struct {
	SocketPath string
	LogLevel   string
	NoColor    bool
}

var globalOpts Options

// NewRoot builds the root command with all subcommands attached. It is
// exported so tests can construct an isolated tree per run.
func NewRoot() *cobra.Command {
	root := &cobra.Command{
		Use:   "httptap",
		Short: "Terminal UI for inspecting live HTTP traffic",
		Long: `httptap attaches to a running Go or C process and shows its HTTP
requests in a TUI. It can also replay HAR files and export captured
traffic to HAR, curl, or raw wire format.`,
		SilenceUsage:  true,
		SilenceErrors: true,
	}
	root.PersistentFlags().StringVar(&globalOpts.SocketPath, "socket",
		"/tmp/httptap.sock", "path to the unix socket the shim writes to")
	root.PersistentFlags().StringVar(&globalOpts.LogLevel, "log-level",
		"warn", "one of debug|info|warn|error")
	root.PersistentFlags().BoolVar(&globalOpts.NoColor, "no-color",
		false, "disable ANSI colour output")

	root.AddCommand(
		newRunCmd(),
		newReplayCmd(),
		newExportCmd(),
		newVersionCmd(),
		newDoctorCmd(),
		newCompletionCmd(),
		newManCmd(),
	)
	return root
}

// Execute is the entry point called by main.
func Execute() {
	if err := NewRoot().Execute(); err != nil {
		fmt.Fprintln(os.Stderr, "httptap:", err)
		os.Exit(1)
	}
}