1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-07 23:02:12 +02:00
kratos/transport/transport.go

87 lines
2.3 KiB
Go
Raw Normal View History

2021-02-17 11:14:47 +02:00
package transport
import (
"context"
"net/url"
2021-02-17 11:14:47 +02:00
// init encoding
_ "github.com/go-kratos/kratos/v2/encoding/json"
_ "github.com/go-kratos/kratos/v2/encoding/proto"
_ "github.com/go-kratos/kratos/v2/encoding/xml"
2021-05-17 15:52:23 +02:00
_ "github.com/go-kratos/kratos/v2/encoding/yaml"
"github.com/go-kratos/kratos/v2/metadata"
2021-02-17 11:14:47 +02:00
)
// Server is transport server.
type Server interface {
Start(context.Context) error
Stop(context.Context) error
2021-02-17 11:14:47 +02:00
}
2021-05-28 09:30:55 +02:00
// Endpointer is registry endpoint.
type Endpointer interface {
Endpoint() (*url.URL, error)
2021-05-28 09:30:55 +02:00
}
// Transporter is transport context value interface.
type Transporter interface {
Kind() string
Endpoint() string
Operation() string
SetOperation(string)
Metadata() metadata.Metadata
// WithMetadata merge new metadata into transport,
// it will override old metadata key value if key exists
WithMetadata(metadata.Metadata)
2021-02-17 11:14:47 +02:00
}
type serverTransportKey struct{}
type clientTransportKey struct{}
// NewServerContext returns a new Context that carries value.
func NewServerContext(ctx context.Context, tr Transporter) context.Context {
return context.WithValue(ctx, serverTransportKey{}, tr)
}
// FromServerContext returns the Transport value stored in ctx, if any.
func FromServerContext(ctx context.Context) (tr Transporter, ok bool) {
tr, ok = ctx.Value(serverTransportKey{}).(Transporter)
return
}
2021-02-17 11:14:47 +02:00
// NewClientContext returns a new Context that carries value.
func NewClientContext(ctx context.Context, tr Transporter) context.Context {
return context.WithValue(ctx, clientTransportKey{}, tr)
2021-02-17 11:14:47 +02:00
}
// FromClientContext returns the Transport value stored in ctx, if any.
func FromClientContext(ctx context.Context) (tr Transporter, ok bool) {
tr, ok = ctx.Value(clientTransportKey{}).(Transporter)
2021-02-17 11:14:47 +02:00
return
}
// SetOperation set operation into context transport.
func SetOperation(ctx context.Context, method string) {
if tr, ok := FromServerContext(ctx); ok {
tr.SetOperation(method)
}
}
// Operation returns the Transport operation from server context.
func Operation(ctx context.Context) string {
if tr, ok := FromServerContext(ctx); ok {
return tr.Operation()
}
return ""
}
// Metadata returns incoming metadata from server transport.
func Metadata(ctx context.Context) metadata.Metadata {
if tr, ok := FromServerContext(ctx); ok {
return tr.Metadata()
}
return metadata.Metadata{}
}