nin

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2023 License: MIT Imports: 20 Imported by: 0

README

Nin Framework

Nin is a client framework for nostr-relayer

Installing

$ go get -u github.com/stc-community/nin

Example

package main

import (
	"time"

	sdk "github.com/nbd-wtf/go-nostr"
	"github.com/stc-community/nin"
)

func main() {
	nin.SetMode(nin.DebugMode)
	tm := time.Now().Add(-5 * time.Second)
	filters := []sdk.Filter{{
		Kinds: []int{sdk.KindTextNote},
		Since: &tm,
	}}
	e, err := nin.Default(&nin.Options{
		Scheme:     "ws",
		Addr:       "127.0.0.1:2700",
		PrivateKey: sdk.GeneratePrivateKey(),
		Filters:    filters,
	})
	if err != nil {
		panic(err)
	}
	e.Add("first.hello.world", func(c *nin.Context) error {
		return c.String("Hello, World")
	})
	e.Run()
}

Another client send event should be like this

ev := nostr.Event{
		PubKey:    pub,
		CreatedAt: time.Now(),
		Kind:      nostr.KindTextNote,
		Tags:      nostr.Tags{{"m", "first"}, {"c", "hello"}, {"a", "world"}},
		Content:   "anything you like",
	}
  • m means moudle
  • c means controller
  • a means action

License

Nin source code is available under the MIT License.

Thanks

go-nostr, gin

Documentation

Index

Constants

View Source
const (
	DebugMode   = "debug"
	ReleaseMode = "release"
	TestMode    = "test"
)
View Source
const AbortIndex int8 = math.MaxInt8 / 2
View Source
const EnvNinMode = "NIN_MODE"

Variables

View Source
var (
	ErrPathInvalid  = errors.New("no valid path")
	ErrPathNotFound = func(path string) error { return fmt.Errorf("%s  path not found", path) }
)
View Source
var DebugPrintRouteFunc func(path, handlerName string, nuHandlers int)

DebugPrintRouteFunc indicates debug log output format.

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Nin to debug errors

View Source
var DefaultWriter io.Writer = os.Stdout
View Source
var (
	ErrPrivateKeyEmpty = errors.New("privateKey can not be empty")
)
View Source
var (
	StatusMap = map[sdk.Status]string{
		sdk.PublishStatusSent:      "sent",
		sdk.PublishStatusFailed:    "failed",
		sdk.PublishStatusSucceeded: "succeed",
	}
)

Functions

func IsDebugging

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(nin.ReleaseMode) to disable debug mode.

func Mode

func Mode() string

Mode returns current gin mode.

func SetMode

func SetMode(value string)

SetMode sets gin mode according to input string.

Types

type Action

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

func (*Action) SetA

func (ac *Action) SetA(a string)

func (*Action) SetC

func (ac *Action) SetC(c string)

func (*Action) SetE

func (ac *Action) SetE(e string)

func (*Action) SetM

func (ac *Action) SetM(m string)

func (*Action) SetP

func (ac *Action) SetP(p string)

type Context

type Context struct {
	Writer    *sdk.Relay
	PublicKey string
	Path      string
	Handlers  HandlersChain // Middleware and final handler functions

	Action *Action
	Event  *sdk.Event
	Status sdk.Status

	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
	Errors errorMsgs

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]any
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

func (*Context) AbortWithError

func (c *Context) AbortWithError(err error) error

func (*Context) Error

func (c *Context) Error(err error) *Error

func (*Context) Get

func (c *Context) Get(key string) (value any, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)

func (*Context) GetBool

func (c *Context) GetBool(key string) (b bool)

GetBool returns the value associated with the key as a boolean.

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (d time.Duration)

GetDuration returns the value associated with the key as a duration.

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (f64 float64)

GetFloat64 returns the value associated with the key as a float64.

func (*Context) GetInt

func (c *Context) GetInt(key string) (i int)

GetInt returns the value associated with the key as an integer.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (i64 int64)

GetInt64 returns the value associated with the key as an integer.

func (*Context) GetString

func (c *Context) GetString(key string) (s string)

GetString returns the value associated with the key as a string.

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]any)

GetStringMap returns the value associated with the key as a map of interfaces.

func (*Context) GetStringMapString

func (c *Context) GetStringMapString(key string) (sms map[string]string)

GetStringMapString returns the value associated with the key as a map of strings.

func (*Context) GetStringMapStringSlice

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key string) (ss []string)

GetStringSlice returns the value associated with the key as a slice of strings.

func (*Context) GetTime

func (c *Context) GetTime(key string) (t time.Time)

GetTime returns the value associated with the key as time.

func (*Context) GetUint

func (c *Context) GetUint(key string) (ui uint)

GetUint returns the value associated with the key as an unsigned integer.

func (*Context) GetUint64

func (c *Context) GetUint64(key string) (ui64 uint64)

GetUint64 returns the value associated with the key as an unsigned integer.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

func (*Context) MustGet

func (c *Context) MustGet(key string) any

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (c *Context) Next() error

func (*Context) Set

func (c *Context) Set(key string, value any)

Set is used to store a new key/value pair exclusively for this context. It also lazies initializes c.Keys if it was not used previously.

func (*Context) String

func (c *Context) String(value string) error

type Engine

type Engine struct {
	IRoutes
	// contains filtered or unexported fields
}

func Default

func Default(opt *Options) (*Engine, error)

func New

func New(opt *Options) (*Engine, error)

func (*Engine) Run

func (e *Engine) Run()

type Error

type Error struct {
	Err  error
	Type ErrorType
	Meta any
}

Error represents a error's specification.

func (Error) Error

func (msg Error) Error() string

Error implements the error interface.

func (*Error) IsType

func (msg *Error) IsType(flags ErrorType) bool

IsType judges one error.

func (*Error) JSON

func (msg *Error) JSON() any

JSON creates a properly formatted JSON

func (*Error) MarshalJSON

func (msg *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface.

func (*Error) SetMeta

func (msg *Error) SetMeta(data any) *Error

SetMeta sets the error's meta data.

func (*Error) SetType

func (msg *Error) SetType(flags ErrorType) *Error

SetType sets the error's type.

func (*Error) Unwrap

func (msg *Error) Unwrap() error

Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap()

type ErrorType

type ErrorType uint64

ErrorType is an unsigned 64-bit error code as defined in the gin spec.

const (
	// ErrorTypeBind is used when Context.Bind() fails.
	ErrorTypeBind ErrorType = 1 << 63
	// ErrorTypeRender is used when Context.Render() fails.
	ErrorTypeRender ErrorType = 1 << 62
	// ErrorTypePrivate indicates a private error.
	ErrorTypePrivate ErrorType = 1 << 0
	// ErrorTypePublic indicates a public error.
	ErrorTypePublic ErrorType = 1 << 1
	// ErrorTypeAny indicates any other error.
	ErrorTypeAny ErrorType = 1<<64 - 1
	// ErrorTypeNu indicates any other error.
	ErrorTypeNu = 2
)

type HandlerFunc

type HandlerFunc func(*Context) error

func CustomRecovery

func CustomRecovery(handle RecoveryFunc) HandlerFunc

CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.

func CustomRecoveryWithWriter

func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc

CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.

func Logger

func Logger() HandlerFunc

func LoggerWithConfig

func LoggerWithConfig(conf LoggerConfig) HandlerFunc

LoggerWithConfig instance a Logger middleware with config.

func Recovery

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter

func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

type HandlersChain

type HandlersChain []HandlerFunc

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. i.e. the last handler is the main one.

type IRoutes

type IRoutes interface {
	Use(handlers ...HandlerFunc) IRoutes
	Add(path string, handlers ...HandlerFunc) IRoutes
	Handlers() map[string]HandlersChain
	Middles() HandlersChain
	Close() error
}

type LogFormatter

type LogFormatter func(params LogFormatterParams) string

LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter

type LogFormatterParams

type LogFormatterParams struct {
	// TimeStamp shows the time after the server returns a response.
	TimeStamp time.Time
	// PublishStatus is relay publish code.
	PublishStatus sdk.Status
	// Latency is how much time the server cost to process a certain request.
	Latency time.Duration
	// ID equals event ID.
	ID string
	// ID equals event PubKey.
	PubKey string
	// Path is a path the client requests.
	Path string
	// ErrorMessage is set if error has occurred in processing the request.
	ErrorMessage string

	// BodySize is the size of the Response Body
	BodySize int
	// Keys are the keys set on the request's context.
	Keys map[string]any
	// contains filtered or unexported fields
}

LogFormatterParams is the structure any formatter will be handed when time to log comes

func (*LogFormatterParams) IsOutputColor

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the log.

func (*LogFormatterParams) PublishStatusColor

func (p *LogFormatterParams) PublishStatusColor() string

PublishStatusColor is the ANSI color for appropriately logging http status code to a terminal.

func (*LogFormatterParams) ResetColor

func (p *LogFormatterParams) ResetColor() string

ResetColor resets all escape attributes.

type LoggerConfig

type LoggerConfig struct {
	// Optional. Default value is nin.defaultLogFormatter
	Formatter LogFormatter

	// Output is a writer where logs are written.
	// Optional. Default value is nin.DefaultWriter.
	Output io.Writer

	// SkipPaths is an url path array which logs are not written.
	// Optional.
	SkipPaths []string
}

LoggerConfig defines the config for Logger middleware.

type Options

type Options struct {
	// ws or wss.
	Scheme string
	// host:port address.
	Addr       string
	PrivateKey string

	SubPubKey []string
	Filters   sdk.Filters
	ErrFun    func(err error)
	// contains filtered or unexported fields
}

func (*Options) PublicKey

func (opt *Options) PublicKey() string

func (*Options) URL

func (opt *Options) URL() string

type RecoveryFunc

type RecoveryFunc func(c *Context, err any)

RecoveryFunc defines the function passable to CustomRecovery.

type Router

type Router struct {
	MiddleWares HandlersChain
	// contains filtered or unexported fields
}

func (*Router) Add

func (r *Router) Add(path string, handlers ...HandlerFunc) IRoutes

func (*Router) Close

func (r *Router) Close() error

func (*Router) Handlers

func (r *Router) Handlers() map[string]HandlersChain

func (*Router) Middles

func (r *Router) Middles() HandlersChain

func (*Router) Use

func (r *Router) Use(middleware ...HandlerFunc) IRoutes

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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