server

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 26 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

Server

This package deals with client-facing APIs. This includes:

  • GraphQL for SPA/Web
  • NATS.io for inter-service messaging
  • REST won't be used unless we find a good way to auto translate - maybe Envoy?

A single function can be exposted via any of these methods. More documenation to come.

Documentation

Overview

///////////////////////////////////////////////////////////////////// David Gurley dmgurley@gmail.com May 2019

//////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////// David Gurley dmgurley@gmail.com June 2018

//////////////////////////////////////////////////////////////////////

Index

Constants

View Source
const (
	EndpointNotImplementedResponse = `{"status": "404", "message": "endpoint not implemented"}`
	NoopResponse                   = `{"status": "200", "message": "noop"}`
	Unauthorized                   = `{"status": "401", "message": "unauthorized"}`
	InternalServerError            = `{"status": "500", "message": "internal server error"}`
)

Variables

View Source
var EndpointNotImplemented = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	json.NewEncoder(w).Encode(EndpointNotImplementedResponse)
})
View Source
var Noop = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(NoopResponse)
})

Functions

func SPAHandler

func SPAHandler(fsys fs.FS) http.Handler

SPAHandler serves a single-page application from fsys: static files with long-lived caching for hashed assets, index.html as the fallback for client-side routes, and precompressed variants (file.br, file.gz) when the build produced them and the client accepts the encoding.

func SetAllowAllWebsocketOrigins

func SetAllowAllWebsocketOrigins(allow bool)

SetAllowAllWebsocketOrigins disables WebSocket origin validation. Development use only; leaving this on in production is a cross-origin (CSRF) hole.

func SetAllowedOrigins

func SetAllowedOrigins(origins []string)

SetAllowedOrigins replaces the WebSocket origin allowlist.

Types

type AccountConnections

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

AccountConnections serves the NATS API inside every tenant account. NATS accounts isolate subjects, so a service connected in its own account is invisible to a caller inside a tenant account; the follower therefore opens one connection per account, serves the API on each, and follows accounts as the admin creates and deletes them (tenant.notify.*).

func (*AccountConnections) Accounts

func (ac *AccountConnections) Accounts() []string

Accounts returns the IDs of the followed accounts currently served.

func (*AccountConnections) AddAccount

func (ac *AccountConnections) AddAccount(accountID, accountName string)

AddAccount connects inside the account and serves the API there. It is idempotent per account ID, skips the primary account, and is a no-op after Close. Failures are logged, not returned, because the follower runs from notifications.

func (*AccountConnections) Close

func (ac *AccountConnections) Close()

Close drops the notification subscriptions and closes every account connection. The primary connection is left alone.

func (*AccountConnections) RemoveAccount

func (ac *AccountConnections) RemoveAccount(accountID string)

RemoveAccount stops serving the account and closes its connection.

type AccountConnector

type AccountConnector func(accountID, jwt, seed string) (nc *nats.Conn, closeFn func(), err error)

AccountConnector opens a NATS connection inside an account with the given credentials and returns it together with a function that closes it. The default connector uses the server's TLS material and MessengerServerURL through package messenger; tests inject a plain one.

type AccountCredentialsProvider

type AccountCredentialsProvider interface {
	ServiceCredentials(accountID, accountName string) (jwt, seed string, err error)
}

AccountCredentialsProvider mints the NATS credentials a service uses to connect inside a tenant account. The admin server implements it for the process that hosts it; a remote service can implement it over GET /api/v1/servicecredentials/{accountName}/{serviceName}.

type AccountRef

type AccountRef struct {
	ID   string
	Name string
}

AccountRef names a tenant account to follow.

type FollowOption

type FollowOption func(*AccountConnections)

FollowOption configures FollowAccounts.

func WithAccountConnector

func WithAccountConnector(c AccountConnector) FollowOption

WithAccountConnector replaces the default connector.

type Response

type Response struct {
	RequestID string `json:"request_id"`
}

type Server

type Server struct {
	ServerOptions   *ServerOptions
	Srv             *http.Server
	Logger          *logger.Logger
	Router          *mux.Router
	Middleware      []*mux.MiddlewareFunc
	Websocket       *Websocket
	MessengerClient *messenger.Client
	TrustedAccounts []string
	LetsEncryptMgr  *letsencrypt.Manager
	// NATSAPI is the bridge that serves the HTTP API over NATS once
	// StartNATSAPI (or ServeNATSAccount) has been called; nil until then.
	NATSAPI *natsapi.Service
	// contains filtered or unexported fields
}

func NewServer

func NewServer(options *ServerOptions) (*Server, error)

func (*Server) AddMessenger

func (server *Server) AddMessenger(options *messenger.ClientOptions) error

func (*Server) FollowAccounts

func (server *Server) FollowAccounts(provider AccountCredentialsProvider, accounts []AccountRef, opts ...FollowOption) (*AccountConnections, error)

FollowAccounts serves the NATS API inside each of accounts (except the server's own messenger account, which StartNATSAPI serves) and keeps following tenant lifecycle notifications on the primary messenger connection. The server must have a messenger client.

func (*Server) Serve

func (server *Server) Serve()

func (*Server) ServeNATSAccount

func (server *Server) ServeNATSAccount(accountID string, nc *nats.Conn) error

ServeNATSAccount serves the HTTP API over NATS on nc, pinned to accountID. The bridge is created on first use. Serving an account that is already served is a no-op.

func (*Server) ServeOpenAPI

func (server *Server) ServeOpenAPI(spec []byte)

ServeOpenAPI registers GET /api/v1/openapi.json returning the given spec. The route is unauthenticated so the API explorer can load it before or after login; specs document the API but contain no secrets.

func (*Server) StartNATSAPI

func (server *Server) StartNATSAPI() error

StartNATSAPI serves the HTTP API over NATS on the server's messenger connection, pinned to the messenger account (ServerOptions. MessengerAccountID, else the client's AccountID). It is idempotent and is called by Serve when ServerOptions.NATSAPI is set; call it directly when the messenger client is attached after Serve (AddMessenger).

func (*Server) Stop

func (server *Server) Stop()

Stop gracefully stops the server and cleans up resources

func (*Server) StopNATSAccount

func (server *Server) StopNATSAccount(accountID string) error

StopNATSAccount stops serving one account; its connection stays open.

type ServerOptions

type ServerOptions struct {
	Application string `json:"application"`
	Component   string `json:"component"`

	// Static TLS certificates (used when LetsEncrypt is not enabled)
	PrivateKey  []byte `json:"private_key"`
	Certificate []byte `json:"certificate"`
	CA          []byte `json:"ca"`

	// Let's Encrypt configuration (optional - if enabled, overrides static certs)
	LetsEncrypt *config.LetsEncryptConfig `json:"lets_encrypt,omitempty"`

	// Shared Let's Encrypt manager (preferred over LetsEncrypt config for all-in-one deployments)
	LetsEncryptManager *letsencrypt.Manager `json:"-"`

	HTTPPort            int      `json:"http_port"`
	PublicKey           string   `json:"public_key"`
	Messenger           bool     `json:"messenger"`
	MessengerAccountID  string   `json:"messenger_account_id"`
	MessengerServerURL  string   `json:"messenger_server_url"`
	MessengerServerName string   `json:"messenger_server_name"`
	MessengerJWT        string   `json:"messenger_jwt"`
	MessengerSeed       string   `json:"messenger_seed"`
	TrustedAccounts     []string `json:"trusted_accounts"`
	BasicAuth           bool     `json:"basic_auth"`
	// NATSAPI serves the HTTP API over NATS as well (package natsapi):
	// the same routes, verbs, payloads, and auth wrappers, reachable by
	// any caller inside the messenger account with only the controller URL
	// and its own credentials. It needs a messenger client.
	NATSAPI bool `json:"nats_api"`
	// NATSAPIService is the subject token and micro service name
	// (api.{service}.{METHOD}.{resource}). Default: Component.
	NATSAPIService string `json:"nats_api_service"`
	// NATSAPIVersion is the micro service version (semver). Default 1.0.0.
	NATSAPIVersion string `json:"nats_api_version"`
	// NATSAPIDescription is published in the micro service info.
	NATSAPIDescription string `json:"nats_api_description"`
	// AllowedOrigins configures the CORS allowlist. When empty it defaults to
	// ["*"]. Auth is header-based (bearer/basic, not cookies) so a wildcard
	// does not leak credentials, but production deployments should pin their
	// own origins here to narrow the surface.
	AllowedOrigins []string `json:"allowed_origins"`
	// this is for http authZ
	Metadata map[string]interface{} `json:"metadata"`
}

Logger per server

func DefaultServerOptions

func DefaultServerOptions() *ServerOptions

func (*ServerOptions) GetCertificate

func (options *ServerOptions) GetCertificate() (tls.Certificate, error)

func (*ServerOptions) GetConnectionString

func (options *ServerOptions) GetConnectionString() string

This is for HTTP server

func (*ServerOptions) GetMetadata

func (options *ServerOptions) GetMetadata(key string) interface{}

Get metadata value from key. Returns nil if key does not exist.

func (*ServerOptions) GetTLSConfig

func (options *ServerOptions) GetTLSConfig() (*tls.Config, error)

GetTLSConfig returns a *tls.Config for the static certificate. It returns a pointer (not a value) because tls.Config contains a sync.RWMutex and must not be copied.

func (*ServerOptions) UseLetsEncrypt

func (options *ServerOptions) UseLetsEncrypt() bool

UseLetsEncrypt returns true if Let's Encrypt is configured and enabled

type Websocket

type Websocket struct {
	Options *WebsocketOptions
	Logger  *logger.Logger
}

implementation of http.Handler

func NewWebsocket

func NewWebsocket(options *WebsocketOptions) *Websocket

func (*Websocket) ServeHTTP

func (websocket *Websocket) ServeHTTP(w http.ResponseWriter, r *http.Request)

type WebsocketOptions

type WebsocketOptions struct {
	Application string `json:"application"`
}

Jump to

Keyboard shortcuts

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