elevate

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2023 License: MIT Imports: 26 Imported by: 0

README

elevate

AWS Lambda Websocket API Proxy integration event bridge to Go net/http.

Usage

elevate is a bridge to convert API Gateway Websocket API with AWS Lambda Proxy integration event request/response and net/http.Request and net/http.ResponseWriter.

package main

import (
	"encoding/json"
	"net/http"

	"github.com/mashiike/elevate"
)

func handler(w http.ResponseWriter, req *http.Request) {
	connectionID := elevate.ConnectionID(req)
	switch elevate.RouteKey(req) {
	case "$connect":
		// do something on connect websocket, for example, store connection id to database.
		w.WriteHeader(http.StatusOK) // return 200 OK, success to connect.
	case "$disconnect":
		// do something on disconnect websocket, for example, delete connection id from database.
		w.WriteHeader(http.StatusOK) // return 200 OK, success to disconnect.
	case "$default":
		// do something on default route
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(connectionID))
	case "notify":
		// default RouteKeySelector emulates $request.body.action
		var data struct {
			Action  string   `json:"action"`
			Targets []string `json:"targets"`
			Message string   `json:"message"`
		}
		if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(http.StatusText(http.StatusBadRequest)))
			return
		}
		for _, target := range data.Targets {
			if err := elevate.PostToConnection(req.Context(), target, []byte(data.Message)); err != nil {
				if elevate.ConnectionIsGone(err) {
					continue
				}
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
				return
			}
		}
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("ok"))
	}
}

func main() {
	elevate.Run(http.HandlerFunc(handler))
}

elevate.Run(http.Handler) and elevate.RunWithOptions(http.Handler, ...elevate.Options)

elevate.Run(http.Handler) and elevate.RunWithOptions(http.Handler, ...elevate.Options) works as below.

  • if running on AWS Lambda(defined AWS_LAMBDA_FUNCTION_NAME or AWS_EXECUTION_ENV environment variable)
    • Call lambda.StartWithOptions()
  • otherwise, run as net/http server with websocket handler.
    • default address ws://localhost:8080/ , you can change elevate.WithLocalAddress(address) option.
    • default route key selector emulates $request.body.action , you can change elevate.WithRouteKeySelector(selector) option.

@connections API

elevate.NewManagementAPIClient() returns github.com/aws/aws-sdk-go-v2/service/apigatewaymanagementapi/apigatewaymanagementapiiface.Client.

you can use @connections API with this client.

and elevate provides suger methods.

  • elevate.PostToConnection(ctx context.Context, connectionID string, data []byte) error
  • elevate.DeleteConnection(ctx context.Context, connectionID string) error
  • elevate.GetConnection(ctx context.Context, connectionID string) (*apigatewaymanagementapi.GetConnectionOutput, error)

if connection not found, this client return err GoneException. suger methods of check this error and return true if connection is not found.

ConnectionID and RouteKey, API Gateway Proxy Request Context

In handler, you can get ConnectionID and RouteKey from *http.Request.

connectionID := elevate.ConnectionID(req)
routeKey := elevate.RouteKey(req)

this is suger interface of elevate.ProxyRequestContext(req).ConnectionID and elevate.ProxyRequestContext(req).RouteKey.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	HTTPHeaderConnectionID = "Elevate-Connection-Id"
	HTTPHeaderRequestID    = "Elevate-Request-Id"
	HTTPHeaderEventType    = "Elevate-Event-Type"
	HTTPHeaderRouteKey     = "Elevate-Route-Key"
)
View Source
var DefaultContentType = "text/plain; charset=utf-8"

DefaultContentType is a default content-type when missing in response.

View Source
var TextMimeTypes = []string{"image/svg+xml", "application/json", "application/xml"}

TextMimeTypes is a list of identified as text.

Functions

func ConnectionID

func ConnectionID(r *http.Request) string

ConnectionID returns connection id from *http.Request.

func ConnectionIsGone

func ConnectionIsGone(err error) bool

ConnectionIsGone returns true if err is GoneException.

func DefaultRouteKeySelector

func DefaultRouteKeySelector(body []byte) (string, error)

DefaultRouteKeySelector is a default RouteKeySelector. it returns "action" key from request body.

func DeleteConnection

func DeleteConnection(ctx context.Context, connectionID string) error

DeleteConnection deletes connectionID.

func EventType

func EventType(r *http.Request) string

EventType returns event type from *http.Request.

func ExitsConnection

func ExitsConnection(ctx context.Context, connectionID string) (bool, error)

ExitsConnection returns true if connectionID exists.

func GetConnection

func GetConnection(ctx context.Context, connectionID string) (*apigatewaymanagementapi.GetConnectionOutput, error)

GetConnection gets connectionID.

func NewManagementAPIClient

func NewManagementAPIClient(ctx context.Context) (*apigatewaymanagementapi.Client, error)

func NewRequest

func NewRequest(event json.RawMessage) (*http.Request, error)

NewRequest creates *net/http.Request from a Request.

func NewRequestWithContext

func NewRequestWithContext(ctx context.Context, event json.RawMessage) (*http.Request, error)

NewRequestWithContext creates *net/http.Request from a Request with context.

func PostToConnection

func PostToConnection(ctx context.Context, connectionID string, data []byte) error

PostToConnection posts data to connectionID.

func RequestID

func RequestID(r *http.Request) string

RequestID returns request id from *http.Request.

func RouteKey

func RouteKey(r *http.Request) string

RouteKey returns route key from *http.Request.

func Run

func Run(mux http.Handler) error

func RunWithOptions

func RunWithOptions(mux http.Handler, options ...Option) error

Types

type Option

type Option func(*runOptions)

func WithAWSConfig

func WithAWSConfig(config *aws.Config) Option

WithAWSConfig sets aws.Config to runOptions. only for AWS Lambda Runtime. default is loaded default config.

func WithContext

func WithContext(ctx context.Context) Option

WithContext sets context.Context to runOptions.

func WithLambdaOptions

func WithLambdaOptions(options ...lambda.Option) Option

WithLambdaOptions sets lambda.Options to runOptions. only for AWS Lambda Runtime.

func WithListener

func WithListener(listener net.Listener) Option

WithListener sets net.Listener to runOptions. only for local.

func WithLocalAdress

func WithLocalAdress(address string) Option

WithLocalAdress sets local address to runOptions.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets slog.Logger to runOptions.

func WithRouteKeySelector

func WithRouteKeySelector(selector RouteKeySelector) Option

WithRouteKeySelector sets RouteKeySelector to runOptions. only for local.

func WithVerbose

func WithVerbose() Option

WithVerbose sets verbose mode to runOptions.

type ResponseWriter

type ResponseWriter struct {
	bytes.Buffer
	// contains filtered or unexported fields
}

ResponeWriter represents a response writer implements http.ResponseWriter.

func NewResponseWriter

func NewResponseWriter() *ResponseWriter

func (*ResponseWriter) Header

func (w *ResponseWriter) Header() http.Header

func (*ResponseWriter) Response

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(code int)

type RouteKeySelector

type RouteKeySelector func(body []byte) (string, error)

RouteKeySelector is a function to select route key from request body. for local.

type WebsocketHTTPBridgeHandler

type WebsocketHTTPBridgeHandler struct {
	Handler http.Handler

	websocket.Upgrader
	// contains filtered or unexported fields
}

func NewWebsocketHTTPBridgeHandler

func NewWebsocketHTTPBridgeHandler(handler http.Handler) *WebsocketHTTPBridgeHandler

func (*WebsocketHTTPBridgeHandler) ServeHTTP

func (*WebsocketHTTPBridgeHandler) SetCallbackURL

func (h *WebsocketHTTPBridgeHandler) SetCallbackURL(callbackURL string)

func (*WebsocketHTTPBridgeHandler) SetLogger

func (h *WebsocketHTTPBridgeHandler) SetLogger(logger *slog.Logger)

func (*WebsocketHTTPBridgeHandler) SetRouteKeySelector

func (h *WebsocketHTTPBridgeHandler) SetRouteKeySelector(selector RouteKeySelector)

func (*WebsocketHTTPBridgeHandler) SetVerbose

func (h *WebsocketHTTPBridgeHandler) SetVerbose(verbose bool)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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