hapi

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package errors provides a way to return detailed information for an rpc request error. The error is normally JSON encoded.

Index

Constants

View Source
const (
	// 服务器配置
	SettingKeyAddr = "addr" // 监听地址

	// tls
	SettingKeyTLS      = "tls"           // 是否启用TLS
	SettingKeyCertFile = "tls_cert_file" // 证书文件路径
	SettingKeyKeyFile  = "tls_key_file"  // 私钥文件路径

	SettingKeyReadTimeout    = "read_timeout"     // 读取超时(秒)
	SettingKeyWriteTimeout   = "write_timeout"    // 写入超时(秒)
	SettingKeyIdleTimeout    = "idle_timeout"     // 空闲超时(秒)
	SettingKeyMaxHeaderBytes = "max_header_bytes" // 最大头部字节数

	// 安全配置
	SettingKeyDebugKey   = "debug_key"   // 调试密钥
	SettingKeyEncryptKey = "encrypt_key" // 加密密钥
)

配置Setting键常量定义

View Source
const (
	RPC_CONTEXT_KEY_HEADER  = "rtx_header"  // 定义需要RPC传输http.Header的ContextKey
	HTTP_HEAD_KEY_DEBUG_KEY = "t_debug_key" // client指定header的此key可以消息不用加密
)

Variables

View Source
var DefaultRoute = func(r *http.Request) (*Service, error) {
	if r.URL.Path == "" {
		return nil, errors.New("path is nil")
	}
	handers := strings.Split(r.URL.Path, "/")
	if len(handers) < 2 {
		return nil, errors.New("path is not /[server]/path")
	}
	service := handers[1]
	if service == "" {
		return nil, errors.New("module server is nil")
	}
	session, err := app.App().GetRouteServer(service,
		selector.WithStrategy(func(services []*registry.Service) selector.Next {
			var nodes []*registry.Node

			for _, service := range services {
				for _, node := range service.Nodes {
					nodes = append(nodes, node)
				}
			}

			var mtx sync.Mutex
			return func() (*registry.Node, error) {
				mtx.Lock()
				defer mtx.Unlock()
				if len(nodes) == 0 {
					return nil, fmt.Errorf("no node")
				}
				index := rand.Intn(int(len(nodes)))
				return nodes[index], nil
			}
		}),
	)
	if err != nil {
		return nil, err
	}
	return &Service{Server: session, Topic: r.URL.Path}, err
}

DefaultRoute 默认路由规则

View Source
var DefaultTransfe = func(service *Service, req *Request, rsp *Response) error {
	return mqrpc.MsgPack(rsp, mqrpc.RpcResult(service.Server.GetRPC().Call(context.TODO(), service.Topic, req)))
}

DefaultTransfe 默认转发规则

Functions

func BadRequest

func BadRequest(id, format string, a ...any) error

BadRequest generates a 400 error.

func Conflict

func Conflict(id, format string, a ...any) error

Conflict generates a 409 error.

func ContextValHeader

func ContextValHeader(ctx context.Context) map[string]*Pair

get Header from context

func Forbidden

func Forbidden(id, format string, a ...any) error

Forbidden generates a 403 error.

func HttpHead

func HttpHead(head map[string]*Pair) mqrpc.IMarshaler

包装一下 Request.Header

func InternalServerError

func InternalServerError(id, format string, a ...any) error

InternalServerError generates a 500 error.

func MethodNotAllowed

func MethodNotAllowed(id, format string, a ...any) error

MethodNotAllowed generates a 405 error.

func NewError

func NewError(id, detail string, code int32) error

NewError generates a custom error.

func NotFound

func NotFound(id, format string, a ...any) error

NotFound generates a 404 error.

func Timeout

func Timeout(id, format string, a ...any) error

Timeout generates a 408 error.

func Unauthorized

func Unauthorized(id, format string, a ...any) error

Unauthorized generates a 401 error.

Types

type Error

type Error struct {
	Id     string `json:"id"`
	Code   int32  `json:"code"`
	Detail string `json:"err"` // old : detail
	Status string `json:"status"`
}

Error implements the error interface.

func ParseError

func ParseError(err string) *Error

ParseError tries to parse a JSON string into an error. If that fails, it will set the given string as the error detail.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Name      string           `msgpack:"name" json:"name"`
	Id        string           `msgpack:"id" json:"id"`
	Timestamp int64            `msgpack:"timestamp" json:"timestamp"`
	Header    map[string]*Pair `msgpack:"header,omitempty" json:"header,omitempty"`
	Data      string           `msgpack:"data,omitempty" json:"data,omitempty"`
}

A HTTP event as RPC, Forwarded by the event handler

type Option

type Option func(*Options)

Option 配置

func Addr

func Addr(addr string) Option

Addr 设置监听地址

func CertFile

func CertFile(certFile string) Option

CertFile 设置证书文件路径

func DebugKey

func DebugKey(key string) Option

DebugKey 调试时的key(可不用加密)

func EncryptKey

func EncryptKey(key string) Option

EncryptKey 设置消息包加密Key

func IdleTimeout

func IdleTimeout(timeout time.Duration) Option

IdleTimeout 设置空闲超时

func KeyFile

func KeyFile(keyFile string) Option

KeyFile 设置私钥文件路径

func MaxHeaderBytes

func MaxHeaderBytes(bytes int) Option

MaxHeaderBytes 设置最大头部字节数

func ReadTimeout

func ReadTimeout(timeout time.Duration) Option

ReadTimeout 设置读取超时

func Route

func Route(s Router) Option

Route 设置路由器

func ServerOpts

func ServerOpts(s []server.Option) Option

ServerOpts ServerOpts

func TLS

func TLS(enable bool) Option

TLS 设置是否启用TLS

func Transfers

func Transfers(t Transfer) Option

RpcHandler 设置rpc处理器

func WriteTimeout

func WriteTimeout(timeout time.Duration) Option

WriteTimeout 设置写入超时

type Options

type Options struct {
	Addr           string   // Settings["Addr"]
	Route          Router   // 控制如何选择rpc服务
	Transfer       Transfer // 控制如何处理api请求
	TLS            bool
	CertFile       string
	KeyFile        string
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
	IdleTimeout    time.Duration
	MaxHeaderBytes int
	DebugKey       string // 调试用(可不用加密调试)(Settings["DebugKey"])
	EncryptKey     string // 消息包加密key(Settings["EncryptKey"])(must 16, 24 or 32 bytes)

	Opts []server.Option // 用来控制Module属性的
}

Options 网关配置项

func NewOptions

func NewOptions(opts ...Option) Options

NewOptions 创建配置

type Pair

type Pair struct {
	Key    string   `msgpack:"key" json:"key"`
	Values []string `msgpack:"values,omitempty" json:"values,omitempty"`
}

header's value

type Request

type Request struct {
	Method string           `msgpack:"method" json:"method"`
	Path   string           `msgpack:"path" json:"path"`
	Header map[string]*Pair `msgpack:"header,omitempty" json:"header,omitempty"`
	Get    map[string]*Pair `msgpack:"get,omitempty" json:"get,omitempty"`
	Post   map[string]*Pair `msgpack:"post,omitempty" json:"post,omitempty"`
	Body   string           `msgpack:"body,omitempty" json:"body,omitempty"` // raw request body; if not application/x-www-form-urlencoded
	Url    string           `msgpack:"url,omitempty" json:"url,omitempty"`
}

A HTTP request as RPC, Forward by the api handler

type Response

type Response struct {
	StatusCode int32            `msgpack:"status_code" json:"status_code"`
	Header     map[string]*Pair `msgpack:"header,omitempty" json:"header,omitempty"`
	Body       string           `msgpack:"body,omitempty" json:"body,omitempty"`
}

A HTTP response as RPC, Expected response for the api handler

type Router

type Router func(r *http.Request) (*Service, error)

Router 路由器定义

type Service

type Service struct {
	// topic
	Topic string // msg_id
	// module server
	Server app.IModuleServerSession
}

Service represents an API service

type Transfer

type Transfer func(service *Service, req *Request, rsp *Response) error

Transfer 转发器定义(Transfer)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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