jhttp

package
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2021 License: BSD-3-Clause Imports: 11 Imported by: 19

Documentation

Overview

Package jhttp implements a bridge from HTTP to JSON-RPC. This permits requests to be submitted to a JSON-RPC server using HTTP as a transport.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/creachadair/jrpc2/handler"
	"github.com/creachadair/jrpc2/jhttp"
)

func main() {
	// Set up a bridge to demonstrate the API.
	b := jhttp.NewBridge(handler.Map{
		"Test": handler.New(func(ctx context.Context, ss []string) (string, error) {
			return strings.Join(ss, " "), nil
		}),
	}, nil)
	defer b.Close()

	hsrv := httptest.NewServer(b)
	defer hsrv.Close()

	rsp, err := http.Post(hsrv.URL, "application/json", strings.NewReader(`{
  "jsonrpc": "2.0",
  "id": 10235,
  "method": "Test",
  "params": ["full", "plate", "and", "packing", "steel"]
}`))
	if err != nil {
		log.Fatalf("POST request failed: %v", err)
	}
	body, err := io.ReadAll(rsp.Body)
	rsp.Body.Close()
	if err != nil {
		log.Fatalf("Reading response body: %v", err)
	}

	fmt.Println(string(body))
}
Output:

{"jsonrpc":"2.0","id":10235,"result":"full plate and packing steel"}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPRequest added in v0.11.2

func HTTPRequest(ctx context.Context) *http.Request

HTTPRequest returns the HTTP request associated with ctx, or nil. The context passed to the JSON-RPC client by the Bridge will contain this value.

Types

type Bridge

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

A Bridge is a http.Handler that bridges requests to a JSON-RPC server.

By default, the bridge accepts only HTTP POST requests with the complete JSON-RPC request message in the body, with Content-Type application/json. Either a single request object or a list of request objects is supported.

If the HTTP request method is not "POST", the bridge reports 405 (Method Not Allowed). If the Content-Type is not application/json, the bridge reports 415 (Unsupported Media Type).

If either a CheckRequest or ParseRequest hook is set, these requirements are disabled, and the hooks are responsible for checking request structure.

If the request completes, whether or not there is an error, the HTTP response is 200 (OK) for ordinary requests or 204 (No Response) for notifications, and the response body contains the JSON-RPC response.

The bridge attaches the inbound HTTP request to the context passed to the client, allowing an EncodeContext callback to retrieve state from the HTTP headers. Use jhttp.HTTPRequest to retrieve the request from the context.

func NewBridge

func NewBridge(mux jrpc2.Assigner, opts *BridgeOptions) Bridge

NewBridge constructs a new Bridge that starts a server on mux and dispatches HTTP requests to it. The server will run until the bridge is closed.

Note that a bridge is not able to push calls or notifications from the server back to the remote client. The bridge client is shared by multiple active HTTP requests, and has no way to know which of the callers the push should be forwarded to. You can enable push on the bridge server and set hooks on the bridge client as usual, but the remote client will not see push messages from the server.

func (Bridge) Close

func (b Bridge) Close() error

Close closes the channel to the server, waits for the server to exit, and reports its exit status.

func (Bridge) ServeHTTP

func (b Bridge) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the required method of http.Handler.

type BridgeOptions added in v0.24.0

type BridgeOptions struct {
	// Options for the bridge client (default nil).
	Client *jrpc2.ClientOptions

	// Options for the bridge server (default nil).
	Server *jrpc2.ServerOptions

	// If non-nil, this function is called to check the HTTP request.  If this
	// function reports an error, the request is rejected.
	//
	// Setting this hook disables the default requirement that the request
	// method be POST and the content-type be application/json.
	CheckRequest func(*http.Request) error

	// If non-nil, this function is called to parse JSON-RPC requests from the
	// HTTP request. If this function reports an error, the request fails.  By
	// default, the bridge uses jrpc2.ParseRequests on the HTTP request body.
	//
	// Setting this hook disables the default requirement that the request
	// method be POST and the content-type be application/json.
	ParseRequest func(*http.Request) ([]*jrpc2.Request, error)
}

BridgeOptions are optional settings for a Bridge. A nil pointer is ready for use and provides default values as described.

type Channel added in v0.1.1

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

A Channel implements a channel.Channel that dispatches requests via HTTP to a user-provided URL. Each message sent to the channel is an HTTP POST request with the message as its body.

func NewChannel added in v0.1.1

func NewChannel(url string, opts *ChannelOptions) *Channel

NewChannel constructs a new channel that posts to the specified URL.

func (*Channel) Close added in v0.1.1

func (c *Channel) Close() error

Close shuts down the channel, discarding any pending responses.

func (*Channel) Recv added in v0.1.1

func (c *Channel) Recv() ([]byte, error)

Recv receives the next available response and reports its body.

func (*Channel) Send added in v0.1.1

func (c *Channel) Send(msg []byte) error

Send forwards msg to the server as the body of an HTTP POST request.

type ChannelOptions added in v0.13.0

type ChannelOptions struct {
	// The HTTP client to use to send requests. If nil, uses http.DefaultClient.
	Client HTTPClient
}

ChannelOptions gives optional parameters for constructing an HTTP channel. A nil *ChannelOptions is ready for use, and provides default options as described.

type HTTPClient added in v0.13.0

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is the interface to an HTTP client used by a Channel. It is compatible with the standard library http.Client type.

Jump to

Keyboard shortcuts

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