You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/transport/transport.go

85 lines
2.1 KiB

4 years ago
package transport
import (
"context"
"net/url"
4 years ago
// 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"
_ "github.com/go-kratos/kratos/v2/encoding/yaml"
4 years ago
)
// Server is transport server.
type Server interface {
Start(context.Context) error
Stop(context.Context) error
4 years ago
}
// Endpointer is registry endpoint.
type Endpointer interface {
Endpoint() (*url.URL, error)
}
// 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 {
// grpc
// http
Kind() Kind
// Server Transport: grpc://127.0.0.1:9000
// Client Transport: discovery:///provider-demo
Endpoint() string
// Service full method selector generated by protobuf
// example: /helloworld.Greeter/SayHello
Operation() string
// http: http.Header
// grpc: metadata.MD
Header() Header
4 years ago
}
// Kind defines the type of Transport
type Kind string
func (k Kind) String() string {
return string(k)
}
// Defines a set of transport kind
const (
KindGRPC Kind = "grpc"
KindHTTP Kind = "http"
)
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
}
4 years ago
// NewClientContext returns a new Context that carries value.
func NewClientContext(ctx context.Context, tr Transporter) context.Context {
return context.WithValue(ctx, clientTransportKey{}, tr)
4 years ago
}
// 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)
4 years ago
return
}