1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-22 03:38:41 +02:00
kratos/transport/transport.go

64 lines
1.6 KiB
Go
Raw Normal View History

2021-02-17 17:14:47 +08:00
package transport
import (
"context"
"net/url"
2021-02-17 17:14:47 +08: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 21:52:23 +08:00
_ "github.com/go-kratos/kratos/v2/encoding/yaml"
2021-02-17 17:14:47 +08:00
)
// Server is transport server.
type Server interface {
Start(context.Context) error
Stop(context.Context) error
2021-02-17 17:14:47 +08:00
}
2021-05-28 15:30:55 +08:00
// Endpointer is registry endpoint.
type Endpointer interface {
Endpoint() (*url.URL, error)
2021-05-28 15:30:55 +08:00
}
// Header is the storage medium used by a Header.
type Header interface {
Get(key string) string
Set(key string, value string)
Keys() []string
}
// Transporter is transport context value interface.
type Transporter interface {
Kind() string
Endpoint() string
Operation() string
Header() Header
2021-02-17 17:14:47 +08: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 17:14:47 +08: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 17:14:47 +08: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 17:14:47 +08:00
return
}