Skip to content

Latest commit

 

History

History
2092 lines (1457 loc) · 59.5 KB

README.md

File metadata and controls

2092 lines (1457 loc) · 59.5 KB

thrift

import "github.com/cloudwego/dynamicgo/thrift"

Index

Constants

const (
    // AnnoKeyDynamicGoDeprecated is used to mark a description as deprecated
    AnnoKeyDynamicGoDeprecated = "dynamicgo.deprecated"
    // AnnoKeyDynamicGoApiNone is used to deal with http response field with api.none annotation
    AnnoKeyDynamicGoApiNone = "api.none"
)
const (
    VERSION_MASK = 0xffff0000
    VERSION_1    = 0x80010000
)
const MaxSkipDepth = types.TB_SKIP_STACK_SIZE - 1

Variables

var (
    CtxKeyIsBodyRoot = &ctxIsBodyRoot
)

func FreeBinaryProtocolBuffer

func FreeBinaryProtocolBuffer(bp *BinaryProtocol)

FreeBinaryProtocol resets the buffer and puts the binary protocol back to sync.Pool

func FreeRequiresBitmap

func FreeRequiresBitmap(b *RequiresBitmap)

FreeRequiresBitmap free the bitmap, but not clear its memory

func GetBinaryMessageHeaderAndFooter

func GetBinaryMessageHeaderAndFooter(methodName string, msgTyp TMessageType, structID FieldID, seqID int32) (header []byte, footer []byte, err error)

GetBinaryMessageHeaderAndFooter writes the message parameters into header and footer

func RegisterAnnotation

func RegisterAnnotation(an Annotation, keys ...string)

RegisterAnnotation register an annotation on specific AnnoScope

func RegisterAnnotationMapper

func RegisterAnnotationMapper(scope AnnoScope, mapper AnnotationMapper, keys ...string)

RegisterAnnotationMapper register a annotation mapper on specific scope

func TypeSize

func TypeSize(t Type) int

TypeSize returns the size of the given type. -1 means variable size (LIST, SET, MAP, STRING) 0 means unknown type

func UnwrapBinaryMessage

func UnwrapBinaryMessage(proto meta.Encoding, buf []byte) (name string, callType TMessageType, seqID int32, structID FieldID, body []byte, err error)

UnwrapBinaryMessage unwraps the message parameters from the buf

func WrapBinaryBody

func WrapBinaryBody(body []byte, methodName string, msgTyp TMessageType, structID FieldID, seqID int32) ([]byte, error)

WrapBinaryMessage wraps the message with header and footer and body

type AnnoID

AnnoID is the unique id of an annotation, which is composed of kind, scope and type:

0xff000000: AnnoKind
0x00ff0000: AnnoScope
0x0000ffff: AnnoType
type AnnoID uint32

func MakeAnnoID

func MakeAnnoID(kind AnnoKind, scope AnnoScope, typ AnnoType) AnnoID

func (AnnoID) Kind

func (t AnnoID) Kind() AnnoKind

Kind returns the kind of the annotation

func (AnnoID) Scope

func (t AnnoID) Scope() AnnoScope

Scope returns the scope of the annotation

func (AnnoID) Type

func (t AnnoID) Type() AnnoType

Type returns the type of the annotation

type AnnoKind

AnnoKind is the kind of annotation, which defines the result handler of Annotation.Make()

type AnnoKind uint8
const (
    // AnnoKindHttpMappping is the kind of http mapping annotation
    // These annotations Make() will return HTTPMapping
    AnnoKindHttpMappping AnnoKind = iota + 1

    // AnnotationKindKeyMapping is the kind of key mapping annotation
    // These annotations Make() will return KeyMapping
    AnnoKindValueMapping

    // AnnotationKindValueMapping is the kind of value mapping annotation
    // These annotations Make() will return ValueMapping
    AnnoKindOptionMapping

    // AnnotationKindOptionMapping is the kind of option mapping annotation
    // These annotations Make() will return OptionMapping
    AnnoKindKeyMapping
)

type AnnoScope

AnnoScope is effective scope of annotation

type AnnoScope uint8
const (
    // AnnoScopeService works on service description
    AnnoScopeService AnnoScope = iota + 1

    // AnnoScopeFunction works on function description
    AnnoScopeFunction

    // AnnoScopeStruct works on struct description
    AnnoScopeStruct

    // AnnoScopeField works on field description
    AnnoScopeField
)

type AnnoType

AnnoType is the specific type of an annotation

type AnnoType uint16

type Annotation

Annotation idl annotation interface

type Annotation interface {
    // unique id of the Annotation
    ID() AnnoID

    // Make makes the handler function under specific values and idl description
    //
    // desc is specific type to its registered AnnoScope:
    //   AnnoScopeService: desc is *parser.Service
    //   AnnoScopeFunction: desc is *parser.Function
    //   AnnoScopeStruct: desc is *parser.StructLike
    //   AnnoScopeField: desc is *parser.Field
    //
    // returned handler SHOULD BE one interface according to its AnnoKind:
    //   AnnoKindHttpMappping: HTTPMapping interface
    //   AnnoKindKeyMapping: KeyMapping interface
    //   AnnoKindKeyMapping: ValueMapping interface
    //   AnnoKindOptionMapping: OptionMapping interface
    Make(ctx context.Context, values []parser.Annotation, desc interface{}) (handler interface{}, err error)
}

func FindAnnotation

func FindAnnotation(key string, scope AnnoScope) Annotation

type AnnotationMapper

AnnotationMapper is used to convert a annotation to equivalent annotations desc is specific to its registered AnnoScope: AnnoScopeService: desc is *parser.Service AnnoScopeFunction: desc is *parser.Function AnnoScopeStruct: desc is *parser.StructLike AnnoScopeField: desc is *parser.Field

type AnnotationMapper interface {
    // Map map a annotation to equivalent annotations
    Map(ctx context.Context, ann []parser.Annotation, desc interface{}, opt Options) (cur []parser.Annotation, next []parser.Annotation, err error)
}

func FindAnnotationMapper

func FindAnnotationMapper(key string, scope AnnoScope) AnnotationMapper

type BinaryEncoding

BinaryEncoding is the implementation of Encoding for binary encoding.

type BinaryEncoding struct{}

func (BinaryEncoding) DecodeBool

func (BinaryEncoding) DecodeBool(b []byte) bool

EncodeFieldEnd encodes a field end.

func (BinaryEncoding) DecodeByte

func (BinaryEncoding) DecodeByte(b []byte) byte

DecodeByte decodes a byte value.

func (BinaryEncoding) DecodeBytes

func (d BinaryEncoding) DecodeBytes(b []byte) (value []byte)

DecodeBinary decodes a binary value.

func (BinaryEncoding) DecodeDouble

func (BinaryEncoding) DecodeDouble(b []byte) float64

DecodeDouble decodes a double value.

func (BinaryEncoding) DecodeInt16

func (BinaryEncoding) DecodeInt16(b []byte) int16

DecodeInt16 decodes a int16 value.

func (BinaryEncoding) DecodeInt32

func (BinaryEncoding) DecodeInt32(b []byte) int32

DecodeInt32 decodes a int32 value.

func (BinaryEncoding) DecodeInt64

func (BinaryEncoding) DecodeInt64(b []byte) int64

DecodeInt64 decodes a int64 value.

func (BinaryEncoding) DecodeString

func (d BinaryEncoding) DecodeString(b []byte) (value string)

DecodeString decodes a string value.

func (BinaryEncoding) EncodeBinary

func (BinaryEncoding) EncodeBinary(b []byte, v []byte)

EncodeBinary encodes a binary value.

func (BinaryEncoding) EncodeBool

func (BinaryEncoding) EncodeBool(b []byte, v bool)

EncodeBool encodes a bool value.

func (BinaryEncoding) EncodeByte

func (BinaryEncoding) EncodeByte(b []byte, v byte)

EncodeByte encodes a byte value.

func (BinaryEncoding) EncodeDouble

func (BinaryEncoding) EncodeDouble(b []byte, v float64)

func (BinaryEncoding) EncodeFieldBegin

func (BinaryEncoding) EncodeFieldBegin(b []byte, t Type, id FieldID)

EncodeFieldBegin encodes a field begin.

func (BinaryEncoding) EncodeInt16

func (BinaryEncoding) EncodeInt16(b []byte, v int16)

EncodeInt16 encodes a int16 value.

func (BinaryEncoding) EncodeInt32

func (BinaryEncoding) EncodeInt32(b []byte, v int32)

EncodeInt32 encodes a int32 value.

func (BinaryEncoding) EncodeInt64

func (BinaryEncoding) EncodeInt64(b []byte, v int64)

EncodeInt64 encodes a int64 value.

func (BinaryEncoding) EncodeString

func (BinaryEncoding) EncodeString(b []byte, v string)

EncodeString encodes a string value.

type BinaryProtocol

BinaryProtocol implements the BinaryProtocol see https://github.com/apache/thrift/blob/master/doc/specs/thrift-binary-protocol.md

type BinaryProtocol struct {
    Buf  []byte
    Read int
}

func NewBinaryProtocol

func NewBinaryProtocol(buf []byte) *BinaryProtocol

NewBinaryProtocol get a new binary protocol from sync.Pool.

func NewBinaryProtocolBuffer

func NewBinaryProtocolBuffer() *BinaryProtocol

NewBinaryProtocolBuffer gets a new binary protocol from sync.Pool and reuse the buffer in pool

func (*BinaryProtocol) DecodeText

func (p *BinaryProtocol) DecodeText(val string, desc *TypeDescriptor, disallowUnknown bool, base64Binary bool, useFieldName bool, asJson bool) error

DecodeText decode special text-encoded val with desc and write it into buffer The encoding of val should be compatible with `EncodeText()` WARNING: this function is not fully implemented, only support json-encoded string for LIST/MAP/SET/STRUCT

func (*BinaryProtocol) EncodeText

func (p *BinaryProtocol) EncodeText(desc *TypeDescriptor, buf *[]byte, byteAsUint8 bool, disallowUnknown bool, base64Binary bool, useFieldName bool, asJson bool) error

EncodeText reads thrift data with descriptor, and converts it to a specail text-protocol string: This protocol is similar to JSON, excepts its key (or field id) IS NOT QUOTED unless it is a string type: - LIST/SET's all elements will be joined with ',', and if asJson is true the entiry value will be wrapped by '[' (start) and ']' (end). - MAP's each pair of key and value will be binded with ':', all elements will be joined with ',', and if asJson is true the entiry value will be wrapped by '{' (start) and '}' (end). - STRUCT's each pair of field (name or id) and value will be binded with ':', all elements will be joined with ',', and if asJson is true the entiry value will be wrapped by '{' (start) and '}' (end). - STRING (including key) will be wrapped by '"' if asJson is true.

func (BinaryProtocol) Left

func (p BinaryProtocol) Left() int

Left returns the left bytes to read

func (*BinaryProtocol) ModifyI32

func (p *BinaryProtocol) ModifyI32(pos int, value int32) error

ModifyI16 write int32 into the buffer at the given position

func (BinaryProtocol) RawBuf

func (p BinaryProtocol) RawBuf() []byte

RawBuf returns the raw buffer of the protocol

func (*BinaryProtocol) ReadAnyWithDesc

func (p *BinaryProtocol) ReadAnyWithDesc(desc *TypeDescriptor, copyString bool, disallowUnknonw bool, useFieldName bool) (interface{}, error)

ReadAnyWithDesc explains thrift data with descriptor and converts it to go interface{} - LIST/SET will be converted to []interface{} - MAP will be converted to map[string]interface{} or map[int]interface{} or map[interface{}]interface (depends on its key type) - STRUCT will be converted to map[FieldID]interface{}

Example

{
	p1, err := NewDescritorFromPath(context.Background(), "../testdata/idl/example2.thrift")
	if err != nil {
		panic(err)
	}
	example2ReqDesc := p1.Functions()["ExampleMethod"].Request().Struct().FieldById(1).Type()
	data, err := ioutil.ReadFile("../testdata/data/example2.bin")
	if err != nil {
		panic(err)
	}

	p := NewBinaryProtocol(data)
	v, err := p.ReadAnyWithDesc(example2ReqDesc, false, false, true)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v", v)
	p = NewBinaryProtocolBuffer()
	err = p.WriteAnyWithDesc(example2ReqDesc, v, true, true, true)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%x", p.RawBuf())
}

func (*BinaryProtocol) ReadBinary

func (p *BinaryProtocol) ReadBinary(copyBytes bool) (value []byte, err error)

ReadBinary ...

func (*BinaryProtocol) ReadBool

func (p *BinaryProtocol) ReadBool() (bool, error)

ReadBool ...

func (*BinaryProtocol) ReadByte

func (p *BinaryProtocol) ReadByte() (value byte, err error)

ReadByte ...

func (*BinaryProtocol) ReadDouble

func (p *BinaryProtocol) ReadDouble() (value float64, err error)

ReadDouble ...

func (*BinaryProtocol) ReadFieldBegin

func (p *BinaryProtocol) ReadFieldBegin() (name string, typeID Type, id FieldID, err error)

ReadFieldBegin ...

func (*BinaryProtocol) ReadFieldEnd

func (p *BinaryProtocol) ReadFieldEnd() error

ReadFieldEnd ...

func (*BinaryProtocol) ReadI16

func (p *BinaryProtocol) ReadI16() (value int16, err error)

ReadI16 ...

func (*BinaryProtocol) ReadI32

func (p *BinaryProtocol) ReadI32() (value int32, err error)

ReadI32 ...

func (*BinaryProtocol) ReadI64

func (p *BinaryProtocol) ReadI64() (value int64, err error)

ReadI64 ...

func (*BinaryProtocol) ReadInt

func (p *BinaryProtocol) ReadInt(t Type) (value int, err error)

ReadInt ...

func (*BinaryProtocol) ReadListBegin

func (p *BinaryProtocol) ReadListBegin() (elemType Type, size int, err error)

ReadListBegin ...

func (*BinaryProtocol) ReadListEnd

func (p *BinaryProtocol) ReadListEnd() error

ReadListEnd ...

func (*BinaryProtocol) ReadMapBegin

func (p *BinaryProtocol) ReadMapBegin() (kType, vType Type, size int, err error)

ReadMapBegin ...

func (*BinaryProtocol) ReadMapEnd

func (p *BinaryProtocol) ReadMapEnd() error

ReadMapEnd ...

func (*BinaryProtocol) ReadMessageBegin

func (p *BinaryProtocol) ReadMessageBegin(copyString bool) (name string, typeID TMessageType, seqID int32, err error)

ReadMessageBegin ...

func (*BinaryProtocol) ReadMessageEnd

func (p *BinaryProtocol) ReadMessageEnd() error

ReadMessageEnd ...

func (*BinaryProtocol) ReadSetBegin

func (p *BinaryProtocol) ReadSetBegin() (elemType Type, size int, err error)

ReadSetBegin ...

func (*BinaryProtocol) ReadSetEnd

func (p *BinaryProtocol) ReadSetEnd() error

ReadSetEnd ...

func (*BinaryProtocol) ReadString

func (p *BinaryProtocol) ReadString(copy bool) (value string, err error)

ReadString ...

func (*BinaryProtocol) ReadStringWithDesc

func (p *BinaryProtocol) ReadStringWithDesc(desc *TypeDescriptor, buf *[]byte, byteAsUint8 bool, disallowUnknown bool, base64Binary bool) error

ReadStringWithDesc explains thrift data with desc and converts to simple string

func (*BinaryProtocol) ReadStructBegin

func (p *BinaryProtocol) ReadStructBegin() (name string, err error)

ReadStructBegin ...

func (*BinaryProtocol) ReadStructEnd

func (p *BinaryProtocol) ReadStructEnd() error

ReadStructEnd ...

func (*BinaryProtocol) Recycle

func (p *BinaryProtocol) Recycle()

Recycle put the protocol back to sync.Pool

func (*BinaryProtocol) Reset

func (p *BinaryProtocol) Reset()

Reset resets the buffer and read position

func (*BinaryProtocol) Skip

func (p *BinaryProtocol) Skip(fieldType Type, useNative bool) (err error)

Skip skips over the value for the given type.

func (*BinaryProtocol) SkipGo

func (p *BinaryProtocol) SkipGo(fieldType Type, maxDepth int) (err error)

SkipGo skips over the value for the given type using Go implementation.

func (*BinaryProtocol) SkipNative

func (p *BinaryProtocol) SkipNative(fieldType Type, maxDepth int) (err error)

Skip skips over teh value for the given type using native C implementation.

func (BinaryProtocol) UnwrapBody

func (p BinaryProtocol) UnwrapBody() (string, TMessageType, int32, FieldID, []byte, error)

UnwrapBody unwraps the message parameters from its buf

func (*BinaryProtocol) WriteAnyWithDesc

func (p *BinaryProtocol) WriteAnyWithDesc(desc *TypeDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error

WriteAnyWithDesc explain desc and val and write them into buffer - LIST/SET will be converted from []interface{} - MAP will be converted from map[string]interface{} or map[int]interface{} - STRUCT will be converted from map[FieldID]interface{}

func (*BinaryProtocol) WriteBinary

func (p *BinaryProtocol) WriteBinary(value []byte) error

WriteBinary ...

func (*BinaryProtocol) WriteBool

func (p *BinaryProtocol) WriteBool(value bool) error

WriteBool ...

func (*BinaryProtocol) WriteByte

func (p *BinaryProtocol) WriteByte(value byte) error

WriteByte ...

func (*BinaryProtocol) WriteDefaultOrEmpty

func (p *BinaryProtocol) WriteDefaultOrEmpty(field *FieldDescriptor) error

WriteDefaultOrEmpty write default value if any, otherwise write zero value

func (*BinaryProtocol) WriteDouble

func (p *BinaryProtocol) WriteDouble(value float64) error

WriteDouble ...

func (*BinaryProtocol) WriteEmpty

func (p *BinaryProtocol) WriteEmpty(desc *TypeDescriptor) error

WriteEmpty write zero value

func (*BinaryProtocol) WriteFieldBegin

func (p *BinaryProtocol) WriteFieldBegin(name string, typeID Type, id FieldID) error

WriteFieldBegin ...

func (*BinaryProtocol) WriteFieldEnd

func (p *BinaryProtocol) WriteFieldEnd() error

WriteFieldEnd ...

func (*BinaryProtocol) WriteFieldStop

func (p *BinaryProtocol) WriteFieldStop() error

WriteFieldStop ...

func (*BinaryProtocol) WriteI16

func (p *BinaryProtocol) WriteI16(value int16) error

WriteI16 ...

func (*BinaryProtocol) WriteI32

func (p *BinaryProtocol) WriteI32(value int32) error

WriteI32 ...

func (*BinaryProtocol) WriteI64

func (p *BinaryProtocol) WriteI64(value int64) error

WriteI64 ...

func (*BinaryProtocol) WriteInt

func (p *BinaryProtocol) WriteInt(t Type, value int) error

WriteInt ...

func (*BinaryProtocol) WriteListBegin

func (p *BinaryProtocol) WriteListBegin(elemType Type, size int) error

WriteListBegin ...

func (*BinaryProtocol) WriteListBeginWithSizePos

func (p *BinaryProtocol) WriteListBeginWithSizePos(elemType Type, size int) (int, error)

WriteListBeginWithSizePos writes the list begin, and return the buffer position of the size data

func (*BinaryProtocol) WriteListEnd

func (p *BinaryProtocol) WriteListEnd() error

WriteListEnd ...

func (*BinaryProtocol) WriteMapBegin

func (p *BinaryProtocol) WriteMapBegin(keyType, valueType Type, size int) error

WriteMapBegin ...

func (*BinaryProtocol) WriteMapBeginWithSizePos

func (p *BinaryProtocol) WriteMapBeginWithSizePos(keyType, valueType Type, size int) (int, error)

WriteMapBeginWithSizePos writes the map begin, and return the buffer position of the size data

func (*BinaryProtocol) WriteMapEnd

func (p *BinaryProtocol) WriteMapEnd() error

WriteMapEnd ...

func (*BinaryProtocol) WriteMessageBegin

func (p *BinaryProtocol) WriteMessageBegin(name string, typeID TMessageType, seqID int32) error

WriteMessageBegin ...

func (*BinaryProtocol) WriteMessageEnd

func (p *BinaryProtocol) WriteMessageEnd() error

WriteMessageEnd ...

func (*BinaryProtocol) WriteSetBegin

func (p *BinaryProtocol) WriteSetBegin(elemType Type, size int) error

WriteSetBegin ...

func (*BinaryProtocol) WriteSetEnd

func (p *BinaryProtocol) WriteSetEnd() error

WriteSetEnd ...

func (*BinaryProtocol) WriteString

func (p *BinaryProtocol) WriteString(value string) error

WriteString ...

func (*BinaryProtocol) WriteStringWithDesc

func (p *BinaryProtocol) WriteStringWithDesc(val string, desc *TypeDescriptor, disallowUnknown bool, base64Binary bool) error

WriteStringWithDesc explain simple string val with desc and convert to thrift data

func (*BinaryProtocol) WriteStructBegin

func (p *BinaryProtocol) WriteStructBegin(name string) error

WriteStructBegin ...

func (*BinaryProtocol) WriteStructEnd

func (p *BinaryProtocol) WriteStructEnd() error

WriteStructEnd ...

type DefaultValue

DefaultValue is the default value of a field

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

func (DefaultValue) GoValue

func (d DefaultValue) GoValue() interface{}

GoValue return the go runtime representation of the default value

func (DefaultValue) JSONValue

func (d DefaultValue) JSONValue() string

JSONValue return the json-encoded representation of the default value

func (DefaultValue) ThriftBinary

func (d DefaultValue) ThriftBinary() string

ThriftBinary return the thrift-binary-encoded representation of the default value

type FieldDescriptor

FieldDescriptor is the runtime descriptor of a field in a struct

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

func (FieldDescriptor) Alias

func (f FieldDescriptor) Alias() string

Alias returns the alias of a field

func (FieldDescriptor) DefaultValue

func (f FieldDescriptor) DefaultValue() *DefaultValue

DefaultValue returns the default value of a field

func (FieldDescriptor) HTTPMappings

func (f FieldDescriptor) HTTPMappings() []HttpMapping

HTTPMappings returns the http-mapping annotations of a field

func (FieldDescriptor) ID

func (f FieldDescriptor) ID() FieldID

ID returns the id of a field

func (FieldDescriptor) IsRequestBase

func (f FieldDescriptor) IsRequestBase() bool

IsRequestBase tells if the field is base.Base

func (FieldDescriptor) IsResponseBase

func (f FieldDescriptor) IsResponseBase() bool

IsResponseBase tells if the field is base.BaseResp

func (FieldDescriptor) Name

func (f FieldDescriptor) Name() string

Name returns the name of a field

func (FieldDescriptor) Required

func (f FieldDescriptor) Required() Requireness

Required return the requiredness of a field

func (FieldDescriptor) Type

func (f FieldDescriptor) Type() *TypeDescriptor

Type returns the type descriptor of a field

func (FieldDescriptor) ValueMapping

func (f FieldDescriptor) ValueMapping() ValueMapping

ValueMapping returns the value-mapping annotation of a field

func (FieldDescriptor) ValueMappingType

func (f FieldDescriptor) ValueMappingType() AnnoType

ValueMappingType returns the value-mapping annotation's type of a field

type FieldID

FieldID is used to identify a field in a struct

type FieldID uint16

type FieldIDMap

FieldIDMap is a map from field id to field descriptor

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

func (FieldIDMap) All

func (fd FieldIDMap) All() (ret []*FieldDescriptor)

All returns all field descriptors

func (FieldIDMap) Get

func (fd FieldIDMap) Get(id FieldID) *FieldDescriptor

Get gets the field descriptor for the given id

func (*FieldIDMap) Set

func (fd *FieldIDMap) Set(id FieldID, f *FieldDescriptor)

Set sets the field descriptor for the given id

func (FieldIDMap) Size

func (fd FieldIDMap) Size() int

Size returns the size of the map

type FieldNameMap

FieldNameMap is a map for field name and field descriptor

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

func (FieldNameMap) All

func (ft FieldNameMap) All() []*FieldDescriptor

All returns all field descriptors

func (*FieldNameMap) Build

func (ft *FieldNameMap) Build()

Build builds the map. It will try to build a trie tree if the dispersion of keys is higher enough (min).

func (FieldNameMap) Get

func (ft FieldNameMap) Get(k string) *FieldDescriptor

Get gets the field descriptor for the given key

func (*FieldNameMap) Set

func (ft *FieldNameMap) Set(key string, field *FieldDescriptor) (exist bool)

Set sets the field descriptor for the given key

func (FieldNameMap) Size

func (ft FieldNameMap) Size() int

Size returns the size of the map

type FunctionDescriptor

FunctionDescriptor idl function descriptor

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

func GetFnDescFromFile

func GetFnDescFromFile(filePath, fnName string, opts Options) *FunctionDescriptor

GetFnDescFromFile get a fucntion descriptor from idl path (relative to your git root) and the function name

func (FunctionDescriptor) Annotations

func (f FunctionDescriptor) Annotations() map[string][]string

Annotations returns the annotations of the function

func (FunctionDescriptor) Endpoints

func (f FunctionDescriptor) Endpoints() []http.Endpoint

Endpoints returns the http endpoints of the function

func (FunctionDescriptor) HasRequestBase

func (f FunctionDescriptor) HasRequestBase() bool

HasRequestBase tells if the function has a base.Base field

func (FunctionDescriptor) Name

func (f FunctionDescriptor) Name() string

Name returns the name of the function

func (FunctionDescriptor) Oneway

func (f FunctionDescriptor) Oneway() bool

Oneway tells if the function is oneway type

func (FunctionDescriptor) Request

func (f FunctionDescriptor) Request() *TypeDescriptor

Request returns the request type descriptor of the function The request arguements is mapped with arguement id and name

func (FunctionDescriptor) Response

func (f FunctionDescriptor) Response() *TypeDescriptor

Response returns the response type descriptor of the function The response arguements is mapped with arguement id

type HttpMapping

HTTPMapping is used to convert http value while running convertion. See also: thrift/annotation/http_mapping.go

type HttpMapping interface {
    // Request get a http value from req
    Request(ctx context.Context, req http.RequestGetter, field *FieldDescriptor) (string, error)

    // Response set a http value into resp
    Response(ctx context.Context, resp http.ResponseSetter, field *FieldDescriptor, val string) error

    // RawEncoding indicates the encoding of the value, it should be meta.EncodingText by default
    Encoding() meta.Encoding
}

type KeyMapping

KeyMapping is used to convert field key while parsing idl. See also: thrift/annotation/key_mapping.go

type KeyMapping interface {
    // Map key to new key
    Map(ctx context.Context, key string) string
}

type OptionMapping

OptionMapping is used to convert thrift.Options while parsing idl. See also: thrift/annotation/option_mapping.go

type OptionMapping interface {
    // Map options to new options
    Map(ctx context.Context, opts Options) Options
}

type Options

Options is options for parsing thrift IDL.

type Options struct {
    // ParseServiceMode indicates how to parse service.
    ParseServiceMode meta.ParseServiceMode

    // MapFieldWay indicates StructDescriptor.FieldByKey() uses alias to map field.
    // By default, we use alias to map, and alias always equals to field name if not given.
    MapFieldWay meta.MapFieldWay

    // ParseFieldRandomRate indicates whether to parse partial fields and is only used for mock test.
    // The value means the possibility of randomly parse and embed one field into StructDescriptor.
    // It must be within (0, 1], and 0 means always parse all fields.
    ParseFieldRandomRate float64

    // ParseEnumAsInt64 indicates whether to parse enum as I64 (default I32).
    ParseEnumAsInt64 bool

    // SetOptionalBitmap indicates to set bitmap for optional fields
    SetOptionalBitmap bool

    // UseDefaultValue indicates to parse and store default value defined on IDL fields.
    UseDefaultValue bool

    // ParseFunctionMode indicates to parse only response or request for a function
    ParseFunctionMode meta.ParseFunctionMode

    // EnableThriftBase indicates to explictly handle thrift/base (see README.md) fields.
    // One field is identified as a thrift base if it satisfies **BOTH** of the following conditions:
    //   1. Its type is 'base.Base' (for request base) or 'base.BaseResp' (for response base);
    //   2. it is on the top layer of the root struct of one function.
    EnableThriftBase bool
}

func NewDefaultOptions

func NewDefaultOptions() Options

NewDefaultOptions creates a default Options.

func (Options) NewDescriptorFromContentWithMethod

func (opts Options) NewDescriptorFromContentWithMethod(ctx context.Context, path, content string, includes map[string]string, isAbsIncludePath bool, methods ...string) (*ServiceDescriptor, error)

NewDescritorFromContentWithMethod creates a ServiceDescriptor from a thrift content and its includes, but only parse specific methods.

func (Options) NewDescriptorFromPathWithMethod

func (opts Options) NewDescriptorFromPathWithMethod(ctx context.Context, path string, includeDirs []string, methods ...string) (*ServiceDescriptor, error)

NewDescritorFromContent creates a ServiceDescriptor from a thrift path and its includes, with specific methods. If methods is empty, all methods will be parsed. The includeDirs is used to find the include files.

func (Options) NewDescritorFromContent

func (opts Options) NewDescritorFromContent(ctx context.Context, path, content string, includes map[string]string, isAbsIncludePath bool) (*ServiceDescriptor, error)

NewDescritorFromContent creates a ServiceDescriptor from a thrift content and its includes, which uses the default options. path is the main thrift file path, content is the main thrift file content. includes is the thrift file content map, and its keys are specific including thrift file path. isAbsIncludePath indicates whether these keys of includes are absolute path. If true, the include path will be joined with the main thrift file path.

func (Options) NewDescritorFromPath

func (opts Options) NewDescritorFromPath(ctx context.Context, path string, includeDirs ...string) (*ServiceDescriptor, error)

NewDescritorFromContent creates a ServiceDescriptor from a thrift path and its includes, which uses the given options. The includeDirs is used to find the include files.

type ParseTarget

ParseTarget indicates the target to parse

type ParseTarget uint8
const (
    Request ParseTarget = iota
    Response
    Exception
)

type Requireness

Requireness is the requireness of a field. See also https://thrift.apache.org/docs/idl.html

type Requireness uint8
const (
    // OptionalRequireness means the field is optional
    OptionalRequireness Requireness = 0
    // DefaultRequireness means the field is default-requireness
    DefaultRequireness Requireness = 1
    // RequiredRequireness means the field is required
    RequiredRequireness Requireness = 2
)

type RequiresBitmap

RequiresBitmap is a bitmap to mark fields

type RequiresBitmap []uint64

func NewRequiresBitmap

func NewRequiresBitmap() *RequiresBitmap

NewRequiresBitmap get bitmap from pool, if pool is empty, create a new one WARN: memory from pool maybe dirty!

func (RequiresBitmap) CheckRequires

func (b RequiresBitmap) CheckRequires(desc *StructDescriptor, writeDefault bool, handler func(field *FieldDescriptor) error) error

CheckRequires scan every bit of the bitmap. When a bit is marked, it will: - if the corresponding field is required-requireness, it reports error - if the corresponding is not required-requireness but writeDefault is true, it will call handler to handle this field

func (RequiresBitmap) CopyTo

func (b RequiresBitmap) CopyTo(to *RequiresBitmap)

CopyTo copy the bitmap to a given bitmap

func (RequiresBitmap) HandleRequires

func (b RequiresBitmap) HandleRequires(desc *StructDescriptor, writeRquired bool, writeDefault bool, writeOptional bool, handler func(field *FieldDescriptor) error) error

CheckRequires scan every bit of the bitmap. When a bit is marked, it will: - if the corresponding field is required-requireness and writeRquired is true, it will call handler to handle this field, otherwise report error - if the corresponding is default-requireness and writeDefault is true, it will call handler to handle this field - if the corresponding is optional-requireness and writeOptional is true, it will call handler to handle this field

func (RequiresBitmap) IsSet

func (b RequiresBitmap) IsSet(id FieldID) bool

IsSet tells if the bit corresponding the given id is marked

func (*RequiresBitmap) Set

func (b *RequiresBitmap) Set(id FieldID, val Requireness)

Set mark the bit corresponding the given id, with the given requireness - RequiredRequireness|DefaultRequireness mark the bit as 1 - OptionalRequireness mark the bit as 0

type ServiceDescriptor

ServiceDescriptor is the runtime descriptor of a service

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

func NewDescritorFromContent

func NewDescritorFromContent(ctx context.Context, path, content string, includes map[string]string, isAbsIncludePath bool) (*ServiceDescriptor, error)

NewDescritorFromContent behaviors like NewDescritorFromPath, besides it uses DefaultOptions.

Example

{
	path := "a/b/main.thrift"
	content := `
	include "base/base.thrift"
	namespace go test.server

	service InboxService {
		base.BaseResp ExampleMethod(1: base.Base req)
	}`
	base := `
	namespace py base
	namespace go base
	namespace java com.bytedance.thrift.base
	
	struct TrafficEnv {
		1: bool Open = false,
		2: string Env = "",
	}
	
	struct Base {
		1: string LogID = "",
		2: string Caller = "",
		3: string Addr = "",
		4: string Client = "",
		5: optional TrafficEnv TrafficEnv,
		6: optional map<string, string> Extra,
	}
	
	struct BaseResp {
		1: string StatusMessage = "",
		2: i32 StatusCode = 0,
		3: optional map<string, string> Extra,
	}
	`

	includes := map[string]string{
		path:                   content,
		"a/b/base/base.thrift": base,
	}

	p1, err := NewDescritorFromContent(context.Background(), path, content, includes, true)
	if err != nil {
		panic(err)
	}
	r1, _ := p1.LookupFunctionByMethod("ExampleMethod")
	fmt.Printf("%#v\n", r1.Response())

	delete(includes, "a/b/base/base.thrift")
	includes["base/base.thrift"] = base

	p2, err := Options{
		ParseFunctionMode: meta.ParseRequestOnly,
	}.NewDescritorFromContent(context.Background(), path, content, includes, false)
	if err != nil {
		panic(err)
	}
	r2, _ := p2.LookupFunctionByMethod("ExampleMethod")
	fmt.Printf("%#v\n", r2.Response())
}

func NewDescritorFromPath

func NewDescritorFromPath(ctx context.Context, path string, includeDirs ...string) (*ServiceDescriptor, error)

NewDescritorFromPath behaviors like NewDescritorFromPath, besides it uses DefaultOptions.

Example

{

	p1, err := NewDescritorFromPath(context.Background(), "../testdata/idl/example.thrift")
	if err != nil {
		panic(err)
	}
	r1, _ := p1.LookupFunctionByMethod("ExampleMethod")
	fmt.Printf("%#v\n", r1.Response())

	p2, err := Options{
		ParseFunctionMode: meta.ParseRequestOnly,
	}.NewDescritorFromPath(context.Background(), "../testdata/idl/example.thrift")
	if err != nil {
		panic(err)
	}
	r2, _ := p2.LookupFunctionByMethod("ExampleMethod")
	fmt.Printf("%#v\n", r2.Response())
}

func (ServiceDescriptor) Annotations

func (s ServiceDescriptor) Annotations() map[string][]string

Annotations returns the annotations of a service

func (ServiceDescriptor) Functions

func (s ServiceDescriptor) Functions() map[string]*FunctionDescriptor

Functions returns all functions in the service

func (*ServiceDescriptor) LookupFunctionByMethod

func (s *ServiceDescriptor) LookupFunctionByMethod(method string) (*FunctionDescriptor, error)

LookupFunctionByMethod lookup function by method name

func (ServiceDescriptor) Name

func (s ServiceDescriptor) Name() string

Name returns the name of the service

type StructDescriptor

StructDescriptor is the runtime descriptor of a STRUCT type

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

func (StructDescriptor) FieldById

func (s StructDescriptor) FieldById(id FieldID) *FieldDescriptor

FieldById finds the field by field id

func (StructDescriptor) FieldByKey

func (s StructDescriptor) FieldByKey(k string) (field *FieldDescriptor)

FieldByName finds the field by key

NOTICE: Options.MapFieldWay can influence the behavior of this method. ep: if Options.MapFieldWay is MapFieldWayName, then field names should be used as key.

func (StructDescriptor) Fields

func (s StructDescriptor) Fields() []*FieldDescriptor

Fields returns all fields in the struct

func (StructDescriptor) GetRequestBase

func (s StructDescriptor) GetRequestBase() *FieldDescriptor

GetRequestBase returns the base.Base field of a STRUCT

func (StructDescriptor) GetResponseBase

func (s StructDescriptor) GetResponseBase() *FieldDescriptor

GetResponseBase returns the base.BaseResp field of a STRUCT

func (StructDescriptor) HttpMappingFields

func (s StructDescriptor) HttpMappingFields() []*FieldDescriptor

GetHttpMappingFields returns the fields with http-mapping annotations

func (StructDescriptor) Len

func (s StructDescriptor) Len() int

Len returns the number of fields in the struct

func (StructDescriptor) Name

func (s StructDescriptor) Name() string

Name returns the name of the struct

func (StructDescriptor) Requires

func (s StructDescriptor) Requires() RequiresBitmap

Fields returns requireness bitmap in the struct. By default, only Requred and Default fields are marked.

type TMessageType

TMessageType is the type of message

type TMessageType int32
const (
    INVALID_TMESSAGE_TYPE TMessageType = 0
    CALL                  TMessageType = 1
    REPLY                 TMessageType = 2
    EXCEPTION             TMessageType = 3
    ONEWAY                TMessageType = 4
)

type Type

Type constants in the Thrift protocol

type Type byte

built-in Types

const (
    STOP   Type = 0
    VOID   Type = 1
    BOOL   Type = 2
    BYTE   Type = 3
    I08    Type = 3
    DOUBLE Type = 4
    I16    Type = 6
    I32    Type = 8
    I64    Type = 10
    STRING Type = 11
    // UTF7   Type = 11
    STRUCT Type = 12
    MAP    Type = 13
    SET    Type = 14
    LIST   Type = 15
    UTF8   Type = 16
    UTF16  Type = 17

    ERROR Type = 255
)

func FromThriftTType

func FromThriftTType(t thrift.TType) Type

FromThriftTType converts apache/thrift.TType to Type

func (Type) IsComplex

func (p Type) IsComplex() bool

IsComplex tells if the type is one of STRUCT, MAP, SET, LIST

func (Type) IsInt

func (p Type) IsInt() bool

IsInt tells if the type is one of I08, I16, I32, I64

func (Type) String

func (p Type) String() string

String for format and print

func (Type) ToThriftTType

func (p Type) ToThriftTType() thrift.TType

ToThriftTType converts Type to apache/thrift.TType

func (Type) Valid

func (p Type) Valid() bool

type TypeDescriptor

TypeDescriptor is the runtime descriptor of a thrift type

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

func FnRequest

func FnRequest(fn *FunctionDescriptor) *TypeDescriptor

FnRequest We assume the request only have one argument and the only argument it the type we want.

func FnResponse

func FnResponse(fn *FunctionDescriptor) *TypeDescriptor

FnResponse get the normal response type

func (TypeDescriptor) Elem

func (d TypeDescriptor) Elem() *TypeDescriptor

Elem returns the element type descriptor of a LIST, SET or MAP type

func (TypeDescriptor) IsBinary

func (d TypeDescriptor) IsBinary() bool

IsBinary tells if the type is binary type ([]byte)

func (TypeDescriptor) Key

func (d TypeDescriptor) Key() *TypeDescriptor

Key returns the key type descriptor of a MAP type

func (TypeDescriptor) Name

func (d TypeDescriptor) Name() string

Name returns the name of the descriptor for struct, it is the struct name; for build-in type, it is the type name.

func (TypeDescriptor) Struct

func (d TypeDescriptor) Struct() *StructDescriptor

Struct returns the struct type descriptor of a STRUCT type

func (TypeDescriptor) Type

func (d TypeDescriptor) Type() Type

Type returns the build-in type of the descriptor

type ValueMapping

ValueMapping is used to convert thrift value while running convertion. See also: thrift/annotation/value_mapping.go

type ValueMapping interface {
    // Read thrift value from p and convert it into out
    Read(ctx context.Context, p *BinaryProtocol, field *FieldDescriptor, out *[]byte) error

    // Write thrift value into p, which is converted from in
    Write(ctx context.Context, p *BinaryProtocol, field *FieldDescriptor, in []byte) error
}

Generated by gomarkdoc