lspbridge

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

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

Go to latest
Published: Nov 1, 2026 License: BSD-3-Clause Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-lsp-bridge/lspbridge

lspbridge — go-lsp-bridge

Docs License Go Coverage

A pure-Go (no cgo) bridge that relays JSON-RPC LSP traffic between a WebSocket and a language-server subprocess's stdio. It adds and strips the Content-Length framing on the stdio side so the WebSocket payload is the bare JSON object, exactly what browser LSP clients such as codemirror-languageserver and @open-rpc/codemirror-lsp expect — dropping a real language server (texlab, gopls, pyright, typescript-language-server, rust-analyzer, …) behind a web editor with a single HTTP handler.

The only dependency is github.com/coder/websocket.

Wire shape

server → client : one JSON-RPC object per WS text frame
client → server : one JSON-RPC object per WS text frame

The bridge owns the stdio Content-Length framing in both directions; the WebSocket carries bare JSON, so a CodeMirror LSP client connects with no adapter.

Features

  • Per-connection subprocess. Each WebSocket spawns its own language server, killed when the socket closes.
  • Two-layer concurrency caps. A process-wide ceiling keeps the host from being saturated; a per-subject ceiling stops one runaway editor (reconnect loop) from starving everyone else. Tag the request with WithSubject and the per-user counter buckets by authenticated identity rather than raw token.
  • Configurable registry. DefaultServers() ships launchers for latex / go / python / typescript / javascript / rust, each overridable per-deployment via a neutral LSPBRIDGE_* environment variable. Bring your own map, or extend the defaults in place — adding a language is one line.
  • Visible failures. A missing binary or a failed spawn sends a JSON-RPC error frame back to the editor instead of silently dropping completions.
  • Progressive enablement. AvailableLanguages() reports which servers are actually resolvable on the host so a client can light up LSP only where it works.

CGO-free, 100% test coverage (including every error branch), gofmt + go vet clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x).

Install

go get github.com/go-lsp-bridge/lspbridge

Usage

Wire HandleWS into any net/http mux. The langKey is whatever your route extracts (path segment, query param, …):

package main

import (
	"log/slog"
	"net/http"

	"github.com/coder/websocket"
	"github.com/go-lsp-bridge/lspbridge"
)

func main() {
	logger := slog.Default()
	accept := &websocket.AcceptOptions{OriginPatterns: []string{"editor.example.com"}}

	http.HandleFunc("/lsp/", func(w http.ResponseWriter, r *http.Request) {
		lang := r.PathValue("lang") // e.g. registered via /lsp/{lang}
		// Tag the request so the per-user concurrency cap keys by identity.
		r = r.WithContext(lspbridge.WithSubject(r.Context(), subjectOf(r)))
		lspbridge.HandleWS(w, r, lang, logger, accept)
	})

	// Advertise only the servers actually installed on this host.
	_ = lspbridge.AvailableLanguages() // ["go", "latex", ...]

	http.ListenAndServe(":8080", nil)
}

func subjectOf(r *http.Request) string { return "anon" }

Override a server binary without rebuilding:

LSPBRIDGE_GOPLS=/opt/toolchains/go/bin/gopls \
LSPBRIDGE_TEXLAB=/usr/local/bin/texlab \
  ./your-server

Or supply an entirely custom registry:

lspbridge.Servers = map[string]lspbridge.LanguageServer{
	"zig": {Lang: "zig", Binary: "zls", EnvOverride: "LSPBRIDGE_ZLS"},
}

API

// HandleWS upgrades r to a WebSocket, spawns the language server for langKey,
// and relays JSON-RPC in both directions until either side closes.
func HandleWS(w http.ResponseWriter, r *http.Request, langKey string,
	logger *slog.Logger, acceptOpts *websocket.AcceptOptions)

// WithSubject tags ctx so the per-user concurrency cap buckets by identity.
func WithSubject(ctx context.Context, subject string) context.Context

// DefaultServers returns a fresh registry with neutral LSPBRIDGE_* overrides.
func DefaultServers() map[string]LanguageServer

// Servers is the registry HandleWS/AvailableLanguages dispatch through;
// initialised to DefaultServers(), replaceable or extensible by the caller.
var Servers map[string]LanguageServer

// AvailableLanguages returns the language ids whose binary resolves on $PATH.
func AvailableLanguages() []string

// EncodeError marshals a JSON-RPC error response.
func EncodeError(id any, code int, msg string) []byte

type LanguageServer struct {
	Lang        string   // canonical key ("latex", "go", …)
	Binary      string   // default executable name
	Args        []string // extra CLI arguments
	EnvOverride string   // env var that, if set to an existing file, wins
}

Tests & coverage

The suite exercises the full WS → subprocess → WS round-trip against a bundled deterministic stub (cmd/fake-lsp), plus unit tests for the framing, registry resolution, concurrency caps, and every pipe/spawn error branch — reaching 100% statement coverage including error paths.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

The exec/WebSocket tests can't run under qemu-user (a host-built stub can't be exec'd for a foreign arch, and there's no real loopback net), so the qemu cross-arch CI lanes set LSPBRIDGE_NO_EXEC=1 to skip them while the pure framing / registry / concurrency logic still runs and validates the code on all six arches. The native ubuntu/macos lane runs the whole thing at 100%.

License

BSD-3-Clause — see LICENSE. Copyright the go-lsp-bridge/lspbridge authors.

Documentation

Overview

Package lspbridge bridges a WebSocket carrying JSON-RPC LSP messages to a language-server subprocess's stdio. Each LSP server gets a per-connection process (texlab / gopls / pyright / typescript- language-server / rust-analyzer / …) keyed by the language id.

Wire shape on the WS :

server → client : one JSON-RPC object per WS text frame
client → server : one JSON-RPC object per WS text frame

The bridge strips + adds the Content-Length framing on the stdio side so the WS payload is the bare JSON, matching what the standard CodeMirror LSP clients expect (e.g. `codemirror-languageserver`, `@open-rpc/codemirror-lsp`).

Binary resolution : a language id resolves to a binary via the Servers registry. Each entry is configurable via an environment variable so operators can override the binary path per-deployment without rebuilding the image. DefaultServers uses a neutral, project-agnostic prefix :

LSPBRIDGE_TEXLAB        — texlab binary path (default: "texlab")
LSPBRIDGE_GOPLS         — gopls binary path  (default: "gopls")
LSPBRIDGE_PYRIGHT       — pyright-langserver (default: "pyright-langserver")
LSPBRIDGE_TS            — typescript-language-server (default: "typescript-language-server")
LSPBRIDGE_RUSTANALYZER  — rust-analyzer      (default: "rust-analyzer")

When the binary isn't on $PATH the bridge writes a JSON-RPC error response back to the client + closes the WS so the editor can surface a single visible failure instead of silently dropping completions.

The registry is a plain map : callers may pass their own by replacing Servers (e.g. `lspbridge.Servers = myMap`) or extend the defaults in place (`lspbridge.Servers["zig"] = …`). Adding a new language is a one-line change ; the handler dispatches by the URL path's lang parameter.

Index

Constants

This section is empty.

Variables

View Source
var Servers = DefaultServers()

Servers is the registry the exported handlers dispatch through. Initialised to DefaultServers; callers may replace it wholesale or mutate it before serving.

Functions

func AvailableLanguages

func AvailableLanguages() []string

AvailableLanguages returns the set of language ids whose binary is actually resolvable on the host. A client uses this for progressive enablement : connecting to the bridge when the host advertises support, and falling back to a simpler autocomplete otherwise.

func DefaultServers

func DefaultServers() map[string]LanguageServer

DefaultServers returns a fresh registry of the common LSP launchers, keyed by canonical language id. Each entry's EnvOverride uses the neutral LSPBRIDGE_* prefix so nothing about this catalogue is tied to a particular host application. Callers can use it as-is, extend it, or ignore it and supply their own map via Servers.

func EncodeError

func EncodeError(id any, code int, msg string) []byte

EncodeError writes a JSON-RPC error response. Used by a handler when the bridge can't be set up before the subprocess even starts.

func HandleWS

func HandleWS(w http.ResponseWriter, r *http.Request, langKey string, logger *slog.Logger, acceptOpts *websocket.AcceptOptions)

HandleWS upgrades the HTTP request to a WebSocket + spawns the per-language LSP. Bidirectional pipe runs until either side closes ; the subprocess is killed on WS close.

langKey : the URL path param ("latex", "go", …) extracted by the caller's mux. Returning quickly on unknown languages keeps the editor's error path clean.

acceptOpts : the caller passes the same websocket.AcceptOptions it uses for the rest of its WS endpoints so the Origin allowlist stays uniform across endpoints. nil = use a permissive default (dev mode).

func WithSubject

func WithSubject(ctx context.Context, subject string) context.Context

WithSubject returns a child context tagged with the per-user counter key. Call this in the HTTP handler before HandleWS so the per-user concurrency cap buckets by the authenticated identity rather than by raw token (which would double the cap during rotation overlap or multi-device use).

Types

type LanguageServer

type LanguageServer struct {
	Lang   string   // canonical key passed via URL path : "latex" / "go" / …
	Binary string   // default executable name
	Args   []string // additional CLI arguments
	// EnvOverride : if non-empty + the env var is set (and points at an
	// existing file), use that path instead of Binary. Lets ops override
	// per-deployment without re-building the image.
	EnvOverride string
}

LanguageServer describes how to launch one LSP for a given language.

Directories

Path Synopsis
cmd
fake-lsp command
fake-lsp is a deterministic LSP-like subprocess used by the lspbridge integration test.
fake-lsp is a deterministic LSP-like subprocess used by the lspbridge integration test.

Jump to

Keyboard shortcuts

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