Hyperserve
БесплатноНе проверенA net/http-shaped Go server library with typed binding, graceful shutdown, WebSockets, JSON-RPC, and optional MCP Streamable HTTP.
Описание
A net/http-shaped Go server library with typed binding, graceful shutdown, WebSockets, JSON-RPC, and optional MCP Streamable HTTP.
README
CI Latest release Go reference License: MIT
HyperServe is a Go server library built on net/http. It leaves routing and
handlers alone, then fills in the work that tends to collect around them:
request binding and validation, middleware, health and readiness, shutdown,
templates and static files, Server-Sent Events, WebSockets, and optional Model
Context Protocol (MCP).
Most Go services start comfortably with a mux and a few handlers. Later they need probes, signal handling, request limits, validation, streaming, or another listener. You can wire those pieces separately. HyperServe is for applications that would rather keep them in one server with one configuration and shutdown path, without taking on a framework-specific router or request context.
For a small service with a handful of routes, plain net/http is usually the
better choice. HyperServe also does not provide an ORM, sessions, a frontend
framework, or application authorization.
Quick start
HyperServe requires Go 1.27.
go get github.com/osauer/hyperserve@latest
package main
import (
"context"
"fmt"
"log"
"github.com/osauer/hyperserve/pkg/server"
)
type GreetRequest struct {
Name string `json:"name" validate:"required,min=2"`
}
type Greeting struct {
Message string `json:"message"`
}
func main() {
srv, err := server.NewServer(
// Health checks listen on :9080, separate from public traffic on :8080.
server.WithHealthServer(),
)
if err != nil {
log.Fatal(err)
}
// JSONHandler limits and decodes the body, validates GreetRequest, and
// turns binding or application errors into JSON responses.
srv.POST("/greetings", server.JSONHandler(
func(_ context.Context, in GreetRequest) (Greeting, error) {
return Greeting{Message: fmt.Sprintf("Hello, %s!", in.Name)}, nil
},
))
// Run handles process signals and waits for active requests before stopping.
// Applications that already own cancellation can use RunContext instead.
if err := srv.Run(); err != nil {
log.Fatal(err)
}
}
Run the server:
go run .
Then, from another terminal:
curl -i http://localhost:8080/greetings \
-H 'Content-Type: application/json' \
--data '{"name":"Ada"}'
NewServer installs request logging, request metrics, and panic recovery.
JSONHandler returns a structured 400 for invalid input and a generic 500
for unexpected application errors.
Why use it?
HyperServe does not introduce an application model. Routes use Go's
method-aware ServeMux patterns, handlers are http.Handler values, and
request cancellation travels through context.Context. Existing handlers and
httptest continue to work.
It also keeps the pieces it starts on the same lifecycle. The HTTP server, health listener, shutdown hooks, internal workers, filesystem roots, and MCP streams are closed through the same shutdown path. Startup failures run that cleanup too.
Configuration is explicit. A bare NewServer() does not read a configuration
file, environment variables, or specially named asset directories. Applications
opt into those sources and decide their precedence.
There is still an ownership line. HyperServe handles transport and server mechanics. The application decides authentication, authorization, data access, session policy, WebSocket reconnection, and deployment topology.
Routes, pages, and assets
Existing handlers can be registered directly. The assembled server is also
available as an http.Handler:
// No adapter is needed for an existing handler.
srv.Handle("/admin/", existingHandler)
// This includes the mux and HyperServe middleware. It can be wrapped, mounted
// in another server, or passed directly to httptest.
handler := srv.Handler()
GET, POST, PUT, PATCH, and the other method helpers use standard
ServeMux patterns, including path values. Handle and HandleFunc remain
available when one handler covers several methods.
JSONHandler is the short path for typed JSON endpoints. BindJSON,
BindQuery, BindForm, and Validate are available when a handler needs
custom headers, streaming, or its own response shape. See the
binding example.
For HTML applications, HyperServe can render html/template files and serve
static assets. Disk roots are off until the application selects them with
WithTemplateDir or WithStaticDir. Static files are confined with
os.Root; HandleStaticChecked returns an error and leaves the route closed
if the root cannot be opened. Embedded assets can be served through an ordinary
handler.
SSE or WebSockets?
Use HTTP for normal request/response work. For a long-lived connection, the direction of communication usually decides:
| Need | Use |
|---|---|
| The server pushes progress, notifications, logs, or dashboard updates | Server-Sent Events (SSE) |
| The client and server can both send at any time | WebSocket |
SSEMessage formats event names and string, byte, or JSON data:
// HyperServe formats the event. The application still chooses authorization,
// event cadence, buffering, and resume behavior.
msg := server.NewSSEMessage(map[string]any{
"progress": 75,
"status": "indexing",
})
msg.Event = "progress"
fmt.Fprint(w, msg)
flusher.Flush() // Send this event without closing the response.
An SSE handler must stop when the request context is cancelled and use server and proxy timeouts that permit a long response. The HTMX + SSE example includes the full loop.
For WebSockets, the server-owned upgrader applies the default same-origin check and records the upgrade with the server's request metrics:
// Prefer the server-owned upgrader to a standalone websocket.Upgrader: it
// keeps the same-origin default and records upgrades with server metrics.
upgrader := srv.WebSocketUpgrader()
Server and outbound client connections have a 1 MiB message limit unless the
application changes it. websocket.Dial accepts caller-owned HTTP clients and
supports headers, subprotocols, TLS verification, and bounded redirects.
Reconnect behavior is left to the application. See the
WebSocket guide and
browser echo example.
Startup, shutdown, and configuration
Run handles SIGINT, SIGTERM, and SIGQUIT. RunContext is for applications
that already own cancellation, such as desktop applications, supervisors, and
larger services.
WithHealthServer puts health, readiness, and liveness on a separate
listener. WithDeferredInit keeps readiness false while a database, cache, or
other dependency starts.
Configuration options are applied from left to right:
// Configuration sources are ignored unless the application opts into them.
// Options run in order, so the final address cannot be replaced by the file
// or environment.
srv, err := server.NewServer(
server.WithConfigFile(configPath),
server.WithEnvironment(),
server.WithAddr("127.0.0.1:8080"),
)
Use DefaultServerOptions with WithOptions when the embedding application
wants to bind one reviewed configuration snapshot. The
configuration example covers the precedence rules.
Security
Security middleware is opt-in:
// Browser headers apply to this route prefix. TLS, sessions, and authorization
// remain separate application decisions.
srv.AddMiddlewareStack("/", server.SecureWeb(srv.Options))
// SecureAPI applies the configured bearer-token validator and per-IP rate limit.
srv.AddMiddlewareStack("/api", server.SecureAPI(srv))
SecureWeb emits a Content Security Policy and other defensive browser
headers, applies configured CORS policy, and emits HSTS when HyperServe serves
TLS. SecureAPI requires an application-provided token validator. Neither
stack defines users, roles, sessions, or resource authorization.
The production guide documents TLS, proxies, health endpoints, filesystem roots, and the remaining application responsibilities.
MCP
MCP is optional and does not change the HTTP or WebSocket APIs:
// MCP shares the HTTP server's middleware and shutdown path. Enabling the
// endpoint does not enable demonstration tools or resources.
srv, err := server.NewServer(
server.WithMCPSupport("payments", "1.0.0"),
)
Applications must add authorization middleware in front of /mcp. HyperServe
supports Streamable HTTP, request-scoped SSE subscriptions, stdio, typed tools,
resources, namespaces, and discovery. Transport versions, limits, and
authorization boundaries are in the MCP guide.
Packages and trade-offs
| Import path | Purpose |
|---|---|
github.com/osauer/hyperserve/pkg/server |
HTTP server, middleware, lifecycle, pages, and MCP wiring |
github.com/osauer/hyperserve/pkg/websocket |
WebSocket upgrader, connection, and outbound dialer |
github.com/osauer/hyperserve/pkg/mcp |
MCP handler, transports, discovery, tools, and resources |
github.com/osauer/hyperserve/pkg/mcp/builtin |
Opt-in demonstration tools and resources |
github.com/osauer/hyperserve/pkg/jsonrpc |
Standalone JSON-RPC 2.0 engine |
The runtime module has one external dependency, golang.org/x/time, for rate
limiting. WebSocket, JSON-RPC, and MCP are maintained in this repository. That
means fewer packages for an application to assemble, but more protocol code for
HyperServe to maintain.
The server, websocket, mcp, and jsonrpc package APIs follow
semantic versioning on the v1 module line. Examples, generated layouts,
commands, and builtin demonstrations are maintained and tested but are not
stable import surfaces. See API stability.
HyperServe does not publish a general throughput number. Its microbenchmarks are useful for comparing revisions on the same machine, not for predicting an application's production performance. See the performance guide.
Scaffold a service
go install github.com/osauer/hyperserve/cmd/hyperserve-init@latest
hyperserve-init --module github.com/acme/payments
cd payments
go run ./cmd/server
The generator creates a Go module, server entry point, and tests. MCP is off because the generator cannot choose the application's authorization policy.
Documentation
- Examples — runnable programs grouped by task
- Go reference — exported API documentation
- Production guide — deployment and security boundaries
- MCP guide — tools, resources, transports, and discovery
- WebSocket guide — server and client behavior
- Architecture — package, configuration, and lifecycle design
- Contributing — local workflow and pull requests
- Security policy — supported releases and private reporting
MIT — see LICENSE. Bugs and usage questions belong in GitHub Issues.
Установка Hyperserve
У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.
▸ github.com/osauer/hyperserveFAQ
Hyperserve MCP бесплатный?
Да, Hyperserve MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для Hyperserve?
Нет, Hyperserve работает без API-ключей и переменных окружения.
Hyperserve — hosted или self-hosted?
Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.
Как установить Hyperserve в Claude Desktop, Claude Code или Cursor?
Открой Hyperserve на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
GitHub
PRs, issues, code search, CI status
автор: GitHubFilesystem
Secure file operations with configurable access controls.
Memory
Knowledge graph-based persistent memory system.
Template MCP Server
A CLI tool to create a new Model Context Protocol server project with TypeScript support, dual transport options, and an extensible structure
автор: mcpdotdirectAmap Maps Mcp Server
MCP server for using the AMap Maps API
автор: duxiaohuiSupabase
Database, auth and storage
автор: SupabaseEverything
Reference / test server with prompts, resources, and tools.
Git
Tools to read, search, and manipulate Git repositories.
Sequential Thinking
Dynamic and reflective problem-solving through thought sequences.
Time
Time and timezone conversion capabilities.
Compare Hyperserve with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории development
