Extension examples
Here is the Request tools extension from Writing extensions in C#, Go and Rust. Each version adds a Base64 tab, a Copy URLs right-click item, a rule that adds an X-Debug: 1 header, and a watcher that turns 5xx responses red. They read the same extension.json, which goes next to the program in the extension’s folder.
| Language | Talks to zhttp with |
|---|---|
| C# | The Zhttp.Extensions library, which handles the protocol for you |
| Go | Its own code, about 200 lines. Standard library only |
| Rust | Its own code, about 140 lines, with serde_json and base64 |
After a change, switch the extension off, build it again and switch it on, as in Change it and try again.
dotnet new console -n request-toolscd request-toolsdotnet add package Zhttp.ExtensionsSet up request-tools.csproj as in Set up the project, then:
using System.Text;using Zhttp.Extensions;
await new Extension() .Viewer("base64", async (shown, capture) => { var exchange = await capture.GetAsync(shown.Session, shown.Id); var text = Encoding.UTF8.GetString(exchange.Request.Body); var decoded = Convert.FromBase64String(text); return View.Plain(Encoding.UTF8.GetString(decoded)); }) .Command("copy-urls", async (picked, capture) => { var urls = new StringBuilder(); foreach (var id in picked.Ids) { var exchange = await capture.GetAsync(picked.Session, id); urls.AppendLine(exchange.Request.Url); } return new CommandResult(Message: $"Copied {picked.Ids.Count} URLs", Copy: urls.ToString()); }) .Hook("debug-header", (hooked, capture) => { hooked.Message.Headers.Add(new Header("X-Debug", "1")); return Task.FromResult(hooked.Message); }) .Watch(async (watched, capture) => { if (watched.Status >= 500) { await capture.MarkAsync(watched.Session, [watched.Id], comment: "Server error", highlight: "red"); } }) .RunAsync();Build and install it:
dotnet publish -c Release -r win-x64 -o "$env:APPDATA\zhttp\extensions\request-tools"dotnet publish -c Release -r osx-arm64 -o "$HOME/Library/Application Support/zhttp/extensions/request-tools"Needs Go.
mkdir request-toolscd request-toolsgo mod init request-toolsPut extension.json in the folder, and this next to it:
package main
import ( "bufio" "encoding/base64" "encoding/json" "errors" "fmt" "log" "os" "strconv" "strings" "sync")
// rpc is one JSON-RPC message: a call, a notification or an answer.type rpc struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *rpcError `json:"error,omitempty"`}
type rpcError struct { Code int `json:"code"` Message string `json:"message"`}
// message is a request or a response. encoding/json turns Body to and from base64.type message struct { Method string `json:"method,omitempty"` URL string `json:"url,omitempty"` Status int `json:"status,omitempty"` Headers [][2]string `json:"headers"` Body []byte `json:"body"`}
type exchange struct { Request message `json:"request"` Response *message `json:"response"`}
// params holds the fields of every call zhttp makes. Each call fills those it has.type params struct { Protocol int Session uint32 ID string IDs []string Status int Message message}
var ( writing sync.Mutex calling sync.Mutex lastID int64 waiting = map[int64]chan rpc{})
func main() { in := bufio.NewReader(os.Stdin) for { line, err := in.ReadBytes('\n') if err != nil { return } var m rpc if err := json.Unmarshal(line, &m); err != nil { log.Fatalf("zhttp sent %q: %v", line, err) } switch m.Method { case "": answered(m) case "shutdown": return default: go answer(m) } }}
// answer runs a call from zhttp and sends back what it returns.func answer(m rpc) { result, err := handle(m.Method, m.Params) if m.ID == nil { if err != nil { log.Printf("%s: %v", m.Method, err) } return } out := rpc{JSONRPC: "2.0", ID: m.ID} if err != nil { out.Error = &rpcError{Code: -32000, Message: err.Error()} } else if out.Result, err = json.Marshal(result); err != nil { out.Error = &rpcError{Code: -32000, Message: err.Error()} } send(out)}
func handle(method string, raw json.RawMessage) (any, error) { var p params if err := json.Unmarshal(raw, &p); err != nil { return nil, err } switch method { case "hello": if p.Protocol != 1 { return nil, fmt.Errorf("zhttp speaks protocol %d, and this extension 1", p.Protocol) } return struct{}{}, nil
case "view": x, err := get(p.Session, p.ID) if err != nil { return nil, err } decoded, err := base64.StdEncoding.DecodeString(string(x.Request.Body)) if err != nil { return nil, err } return map[string]string{"format": "text", "text": string(decoded)}, nil
case "command": var urls strings.Builder for _, id := range p.IDs { x, err := get(p.Session, id) if err != nil { return nil, err } urls.WriteString(x.Request.URL + "\n") } return map[string]string{"message": fmt.Sprintf("Copied %d URLs", len(p.IDs)), "copy": urls.String()}, nil
case "hook": p.Message.Headers = append(p.Message.Headers, [2]string{"X-Debug", "1"}) return map[string]message{"message": p.Message}, nil
case "watched": if p.Status >= 500 { mark := map[string]any{"session": p.Session, "ids": []string{p.ID}, "comment": "Server error", "highlight": "red"} return nil, call("mark", mark, nil) } return nil, nil } return nil, fmt.Errorf("this extension has no method %q", method)}
func get(session uint32, id string) (exchange, error) { var x exchange err := call("get", map[string]any{"session": session, "id": id}, &x) return x, err}
// call calls zhttp and waits for its answer, which main hands to answered.func call(method string, p any, result any) error { raw, err := json.Marshal(p) if err != nil { return err } calling.Lock() lastID++ id := lastID reply := make(chan rpc, 1) waiting[id] = reply calling.Unlock() send(rpc{JSONRPC: "2.0", ID: json.RawMessage(strconv.FormatInt(id, 10)), Method: method, Params: raw}) m := <-reply if m.Error != nil { return errors.New(m.Error.Message) } if result == nil { return nil } return json.Unmarshal(m.Result, result)}
func answered(m rpc) { id, _ := strconv.ParseInt(string(m.ID), 10, 64) calling.Lock() reply := waiting[id] delete(waiting, id) calling.Unlock() if reply == nil { log.Fatalf("zhttp answered call %s, which this extension never made", m.ID) } reply <- m}
func send(m rpc) { line, err := json.Marshal(m) if err != nil { log.Fatal(err) } writing.Lock() defer writing.Unlock() if _, err := os.Stdout.Write(append(line, '\n')); err != nil { log.Fatal(err) }}Build and install it:
$dir = "$env:APPDATA\zhttp\extensions\request-tools"go build -o "$dir\request-tools.exe"Copy-Item extension.json $dirdir="$HOME/Library/Application Support/zhttp/extensions/request-tools"go build -o "$dir/request-tools"cp extension.json "$dir"Go builds for the other system too: set GOOS to windows or darwin, and GOARCH to amd64 or arm64, before go build.
Needs Rust.
cargo new request-toolscd request-toolscargo add base64 serde_jsonPut extension.json in the folder, and replace src/main.rs with:
use std::collections::HashMap;use std::io::{self, BufRead, Write};use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{LazyLock, Mutex, mpsc};use std::thread;
use base64::prelude::{BASE64_STANDARD, Engine as _};use serde_json::{Value, json};
static LAST_ID: AtomicI64 = AtomicI64::new(0);static WAITING: LazyLock<Mutex<HashMap<i64, mpsc::Sender<Value>>>> = LazyLock::new(Default::default);
fn main() { for line in io::stdin().lock().lines() { let line = line.expect("reading from zhttp"); let msg: Value = serde_json::from_str(&line).expect("zhttp sent a line that is not JSON"); match msg["method"].as_str() { None => answered(msg), Some("shutdown") => return, Some(method) => { let method = method.to_string(); thread::spawn(move || answer(&method, msg)); } } }}
// Runs a call from zhttp and sends back what it returns.fn answer(method: &str, msg: Value) { let result = handle(method, &msg["params"]); let Some(id) = msg.get("id") else { if let Err(e) = result { eprintln!("{method}: {e}"); } return; }; match result { Ok(result) => send(json!({ "jsonrpc": "2.0", "id": id, "result": result })), Err(e) => { send(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32000, "message": e } })) } }}
fn handle(method: &str, p: &Value) -> Result<Value, String> { match method { "hello" => { if p["protocol"] != 1 { return Err(format!( "zhttp speaks protocol {}, and this extension 1", p["protocol"] )); } Ok(json!({})) }
"view" => { let x = get(&p["session"], &p["id"])?; let body = base64(&x["request"]["body"])?; let decoded = BASE64_STANDARD.decode(&body).map_err(|e| e.to_string())?; Ok(json!({ "format": "text", "text": String::from_utf8_lossy(&decoded) })) }
"command" => { let ids = p["ids"].as_array().ok_or("no ids")?; let mut urls = String::new(); for id in ids { let x = get(&p["session"], id)?; urls += x["request"]["url"].as_str().ok_or("no url")?; urls += "\n"; } Ok(json!({ "message": format!("Copied {} URLs", ids.len()), "copy": urls })) }
"hook" => { let mut message = p["message"].clone(); message["headers"] .as_array_mut() .ok_or("no headers")? .push(json!(["X-Debug", "1"])); Ok(json!({ "message": message })) }
"watched" => { if p["status"].as_i64().ok_or("no status")? >= 500 { call( "mark", json!({ "session": p["session"], "ids": [p["id"]], "comment": "Server error", "highlight": "red" }), )?; } Ok(Value::Null) }
_ => Err(format!("this extension has no method {method:?}")), }}
// A body as zhttp sends it: base64.fn base64(body: &Value) -> Result<Vec<u8>, String> { BASE64_STANDARD .decode(body.as_str().ok_or("no body")?) .map_err(|e| e.to_string())}
fn get(session: &Value, id: &Value) -> Result<Value, String> { call("get", json!({ "session": session, "id": id }))}
// Calls zhttp and waits for its answer, which main hands to answered.fn call(method: &str, params: Value) -> Result<Value, String> { let id = LAST_ID.fetch_add(1, Ordering::SeqCst) + 1; let (reply, answer) = mpsc::channel(); WAITING.lock().unwrap().insert(id, reply); send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })); let msg = answer.recv().map_err(|e| e.to_string())?; match msg.get("error") { Some(error) => Err(error["message"] .as_str() .expect("zhttp sent an error with no message") .to_string()), None => Ok(msg["result"].clone()), }}
fn answered(msg: Value) { let id = msg["id"].as_i64().expect("zhttp answered with no id"); let reply = WAITING .lock() .unwrap() .remove(&id) .expect("zhttp answered a call this extension never made"); reply.send(msg).unwrap();}
fn send(msg: Value) { let mut out = io::stdout().lock(); writeln!(out, "{msg}").expect("writing to zhttp"); out.flush().expect("writing to zhttp");}Build and install it:
cargo build --release$dir = "$env:APPDATA\zhttp\extensions\request-tools"New-Item -ItemType Directory -Force $dirCopy-Item target\release\request-tools.exe, extension.json $dircargo build --releasedir="$HOME/Library/Application Support/zhttp/extensions/request-tools"mkdir -p "$dir"cp target/release/request-tools extension.json "$dir"How the Go and Rust versions work
Section titled “How the Go and Rust versions work”Without the C# library, the program speaks the protocol itself:
mainreads zhttp’s messages one line at a time. A line with nomethodis zhttp’s answer to a call the program made, andmainhands it to the call that’s waiting for it.shutdownends the program.- Every other call from zhttp runs on its own goroutine (Go) or thread (Rust), so
mainkeeps reading while a handler waits. The Base64 tab, for one, calls zhttp’sgetand waits for the answer. handledoes the work for each method and returns a result or an error, andanswersends that back with the call’sid. Awatchedcall has noid, so its errors go to standard error, which zhttp keeps inextension.log.sendwrites one message per line and holds a lock while it writes, so two answers never mix on standard output.