Initial QSfera import
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
type netListener struct{}
|
||||
|
||||
// getNetListener Get net.Listener from ListenOptions.
|
||||
func getNetListener(o *ListenOptions) net.Listener {
|
||||
if o.Context == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if l, ok := o.Context.Value(netListener{}).(net.Listener); ok && l != nil {
|
||||
return l
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// headers is a package for internal micro global constants
|
||||
package headers
|
||||
|
||||
const (
|
||||
// Message header is a header for internal message communication.
|
||||
Message = "Micro-Topic"
|
||||
// Request header is a message header for internal request communication.
|
||||
Request = "Micro-Service"
|
||||
// Error header contains an error message.
|
||||
Error = "Micro-Error"
|
||||
// Endpoint header.
|
||||
Endpoint = "Micro-Endpoint"
|
||||
// Method header.
|
||||
Method = "Micro-Method"
|
||||
// ID header.
|
||||
ID = "Micro-ID"
|
||||
// Prefix used to prefix headers.
|
||||
Prefix = "Micro-"
|
||||
// Namespace header.
|
||||
Namespace = "Micro-Namespace"
|
||||
// Protocol header.
|
||||
Protocol = "Micro-Protocol"
|
||||
// Target header.
|
||||
Target = "Micro-Target"
|
||||
// ContentType header.
|
||||
ContentType = "Content-Type"
|
||||
// SpanID header.
|
||||
SpanID = "Micro-Span-ID"
|
||||
// TraceIDKey header.
|
||||
TraceIDKey = "Micro-Trace-ID"
|
||||
// Stream header.
|
||||
Stream = "Micro-Stream"
|
||||
)
|
||||
@@ -0,0 +1,204 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
log "go-micro.dev/v4/logger"
|
||||
"go-micro.dev/v4/util/buf"
|
||||
)
|
||||
|
||||
type httpTransportClient struct {
|
||||
dialOpts DialOptions
|
||||
conn net.Conn
|
||||
ht *httpTransport
|
||||
|
||||
// request must be stored for response processing
|
||||
req chan *http.Request
|
||||
buff *bufio.Reader
|
||||
addr string
|
||||
|
||||
// local/remote ip
|
||||
local string
|
||||
remote string
|
||||
reqList []*http.Request
|
||||
|
||||
sync.RWMutex
|
||||
|
||||
once sync.Once
|
||||
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Local() string {
|
||||
return h.local
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Remote() string {
|
||||
return h.remote
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Send(m *Message) error {
|
||||
logger := h.ht.Options().Logger
|
||||
|
||||
header := make(http.Header)
|
||||
for k, v := range m.Header {
|
||||
header.Set(k, v)
|
||||
}
|
||||
|
||||
b := buf.New(bytes.NewBuffer(m.Body))
|
||||
defer func() {
|
||||
if err := b.Close(); err != nil {
|
||||
logger.Logf(log.ErrorLevel, "failed to close buffer: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
req := &http.Request{
|
||||
Method: http.MethodPost,
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: h.addr,
|
||||
},
|
||||
Header: header,
|
||||
Body: b,
|
||||
ContentLength: int64(b.Len()),
|
||||
Host: h.addr,
|
||||
Close: h.dialOpts.ConnClose,
|
||||
}
|
||||
|
||||
if !h.dialOpts.Stream {
|
||||
h.Lock()
|
||||
if h.closed {
|
||||
h.Unlock()
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
h.reqList = append(h.reqList, req)
|
||||
|
||||
select {
|
||||
case h.req <- h.reqList[0]:
|
||||
h.reqList = h.reqList[1:]
|
||||
default:
|
||||
}
|
||||
h.Unlock()
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return req.Write(h.conn)
|
||||
|
||||
}
|
||||
|
||||
// Recv receives a message.
|
||||
func (h *httpTransportClient) Recv(msg *Message) (err error) {
|
||||
if msg == nil {
|
||||
return errors.New("message passed in is nil")
|
||||
}
|
||||
|
||||
var req *http.Request
|
||||
|
||||
if !h.dialOpts.Stream {
|
||||
rc, ok := <-h.req
|
||||
if !ok {
|
||||
h.Lock()
|
||||
if len(h.reqList) == 0 {
|
||||
h.Unlock()
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
rc = h.reqList[0]
|
||||
h.reqList = h.reqList[1:]
|
||||
h.Unlock()
|
||||
}
|
||||
|
||||
req = rc
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err = h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
h.Lock()
|
||||
defer h.Unlock()
|
||||
|
||||
if h.closed {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
rsp, err := http.ReadResponse(h.buff, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err = rsp.Body.Close(); err != nil {
|
||||
err = errors.Wrap(err, "failed to close body")
|
||||
}
|
||||
}()
|
||||
|
||||
b, err := io.ReadAll(rsp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
return errors.New(rsp.Status + ": " + string(b))
|
||||
}
|
||||
|
||||
msg.Body = b
|
||||
|
||||
if msg.Header == nil {
|
||||
msg.Header = make(map[string]string, len(rsp.Header))
|
||||
}
|
||||
|
||||
for k, v := range rsp.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportClient) Close() error {
|
||||
if !h.dialOpts.Stream {
|
||||
h.once.Do(func() {
|
||||
h.Lock()
|
||||
h.buff.Reset(nil)
|
||||
h.closed = true
|
||||
h.Unlock()
|
||||
close(h.req)
|
||||
})
|
||||
|
||||
return h.conn.Close()
|
||||
}
|
||||
|
||||
err := h.conn.Close()
|
||||
h.once.Do(func() {
|
||||
h.Lock()
|
||||
h.buff.Reset(nil)
|
||||
h.closed = true
|
||||
h.Unlock()
|
||||
close(h.req)
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
log "go-micro.dev/v4/logger"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
)
|
||||
|
||||
type httpTransportListener struct {
|
||||
ht *httpTransport
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Addr() string {
|
||||
return h.listener.Addr().String()
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Close() error {
|
||||
return h.listener.Close()
|
||||
}
|
||||
|
||||
func (h *httpTransportListener) Accept(fn func(Socket)) error {
|
||||
// Create handler mux
|
||||
// TODO: see if we should make a plugin out of the mux
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Register our transport handler
|
||||
mux.HandleFunc("/", h.newHandler(fn))
|
||||
|
||||
// Get optional handlers
|
||||
// TODO: This needs to be documented clearer, and examples provided
|
||||
if h.ht.opts.Context != nil {
|
||||
handlers, ok := h.ht.opts.Context.Value("http_handlers").(map[string]http.Handler)
|
||||
if ok {
|
||||
for pattern, handler := range handlers {
|
||||
mux.Handle(pattern, handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Server ONLY supports HTTP1 + H2C
|
||||
srv := &http.Server{
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: time.Second * 5,
|
||||
}
|
||||
|
||||
// insecure connection use h2c
|
||||
if !(h.ht.opts.Secure || h.ht.opts.TLSConfig != nil) {
|
||||
srv.Handler = h2c.NewHandler(mux, &http2.Server{})
|
||||
}
|
||||
|
||||
return srv.Serve(h.listener)
|
||||
}
|
||||
|
||||
// newHandler creates a new HTTP transport handler passed to the mux.
|
||||
func (h *httpTransportListener) newHandler(serveConn func(Socket)) func(rsp http.ResponseWriter, req *http.Request) {
|
||||
logger := h.ht.opts.Logger
|
||||
|
||||
return func(rsp http.ResponseWriter, req *http.Request) {
|
||||
var (
|
||||
buf *bufio.ReadWriter
|
||||
con net.Conn
|
||||
)
|
||||
|
||||
// HTTP1: read a regular request
|
||||
if req.ProtoMajor == 1 {
|
||||
b, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
http.Error(rsp, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
req.Body = io.NopCloser(bytes.NewReader(b))
|
||||
|
||||
// Hijack the conn
|
||||
// We also don't close the connection here, as it will be closed by
|
||||
// the httpTransportSocket
|
||||
hj, ok := rsp.(http.Hijacker)
|
||||
if !ok {
|
||||
// We're screwed
|
||||
http.Error(rsp, "cannot serve conn", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
conn, bufrw, err := hj.Hijack()
|
||||
if err != nil {
|
||||
http.Error(rsp, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
logger.Logf(log.ErrorLevel, "Failed to close TCP connection: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
buf = bufrw
|
||||
con = conn
|
||||
}
|
||||
|
||||
// Buffered reader
|
||||
bufr := bufio.NewReader(req.Body)
|
||||
|
||||
// Save the request
|
||||
ch := make(chan *http.Request, 1)
|
||||
ch <- req
|
||||
|
||||
// Create a new transport socket
|
||||
sock := &httpTransportSocket{
|
||||
ht: h.ht,
|
||||
w: rsp,
|
||||
r: req,
|
||||
rw: buf,
|
||||
buf: bufr,
|
||||
ch: ch,
|
||||
conn: con,
|
||||
local: h.Addr(),
|
||||
remote: req.RemoteAddr,
|
||||
closed: make(chan bool),
|
||||
}
|
||||
|
||||
// Execute the socket
|
||||
serveConn(sock)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
proxyAuthHeader = "Proxy-Authorization"
|
||||
)
|
||||
|
||||
func getURL(addr string) (*url.URL, error) {
|
||||
r := &http.Request{
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: addr,
|
||||
},
|
||||
}
|
||||
|
||||
return http.ProxyFromEnvironment(r)
|
||||
}
|
||||
|
||||
type pbuffer struct {
|
||||
net.Conn
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (p *pbuffer) Read(b []byte) (int, error) {
|
||||
return p.r.Read(b)
|
||||
}
|
||||
|
||||
func proxyDial(conn net.Conn, addr string, proxyURL *url.URL) (_ net.Conn, err error) {
|
||||
defer func() {
|
||||
if err != nil {
|
||||
// trunk-ignore(golangci-lint/errcheck)
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
r := &http.Request{
|
||||
Method: http.MethodConnect,
|
||||
URL: &url.URL{Host: addr},
|
||||
Header: map[string][]string{"User-Agent": {"micro/latest"}},
|
||||
}
|
||||
|
||||
if user := proxyURL.User; user != nil {
|
||||
u := user.Username()
|
||||
p, _ := user.Password()
|
||||
auth := []byte(u + ":" + p)
|
||||
basicAuth := base64.StdEncoding.EncodeToString(auth)
|
||||
r.Header.Add(proxyAuthHeader, "Basic "+basicAuth)
|
||||
}
|
||||
|
||||
if err := r.Write(conn); err != nil {
|
||||
return nil, fmt.Errorf("failed to write the HTTP request: %w", err)
|
||||
}
|
||||
|
||||
br := bufio.NewReader(conn)
|
||||
|
||||
rsp, err := http.ReadResponse(br, r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading server HTTP response: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err = rsp.Body.Close()
|
||||
}()
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
dump, err := httputil.DumpResponse(rsp, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to do connect handshake, status code: %s", rsp.Status)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
|
||||
}
|
||||
|
||||
return &pbuffer{Conn: conn, r: br}, nil
|
||||
}
|
||||
|
||||
// Creates a new connection.
|
||||
func newConn(dial func(string) (net.Conn, error)) func(string) (net.Conn, error) {
|
||||
return func(addr string) (net.Conn, error) {
|
||||
// get the proxy url
|
||||
proxyURL, err := getURL(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// set to addr
|
||||
callAddr := addr
|
||||
|
||||
// got proxy
|
||||
if proxyURL != nil {
|
||||
callAddr = proxyURL.Host
|
||||
}
|
||||
|
||||
// dial the addr
|
||||
c, err := dial(callAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// do proxy connect if we have proxy url
|
||||
if proxyURL != nil {
|
||||
c, err = proxyDial(c, addr, proxyURL)
|
||||
}
|
||||
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type httpTransportSocket struct {
|
||||
w http.ResponseWriter
|
||||
|
||||
// the hijacked when using http 1
|
||||
conn net.Conn
|
||||
ht *httpTransport
|
||||
r *http.Request
|
||||
rw *bufio.ReadWriter
|
||||
|
||||
// for the first request
|
||||
ch chan *http.Request
|
||||
|
||||
// h2 things
|
||||
buf *bufio.Reader
|
||||
// indicate if socket is closed
|
||||
closed chan bool
|
||||
|
||||
// local/remote ip
|
||||
local string
|
||||
remote string
|
||||
|
||||
mtx sync.RWMutex
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Local() string {
|
||||
return h.local
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Remote() string {
|
||||
return h.remote
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Recv(msg *Message) error {
|
||||
if msg == nil {
|
||||
return errors.New("message passed in is nil")
|
||||
}
|
||||
|
||||
if msg.Header == nil {
|
||||
msg.Header = make(map[string]string, len(h.r.Header))
|
||||
}
|
||||
|
||||
if h.r.ProtoMajor == 1 {
|
||||
return h.recvHTTP1(msg)
|
||||
}
|
||||
|
||||
return h.recvHTTP2(msg)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Send(msg *Message) error {
|
||||
// we need to lock to protect the write
|
||||
h.mtx.RLock()
|
||||
defer h.mtx.RUnlock()
|
||||
|
||||
if h.r.ProtoMajor == 1 {
|
||||
return h.sendHTTP1(msg)
|
||||
}
|
||||
|
||||
return h.sendHTTP2(msg)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) Close() error {
|
||||
h.mtx.Lock()
|
||||
defer h.mtx.Unlock()
|
||||
|
||||
select {
|
||||
case <-h.closed:
|
||||
return nil
|
||||
default:
|
||||
// Close the channel
|
||||
close(h.closed)
|
||||
|
||||
// Close the buffer
|
||||
if err := h.r.Body.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) error(m *Message) error {
|
||||
if h.r.ProtoMajor == 1 {
|
||||
rsp := &http.Response{
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(bytes.NewReader(m.Body)),
|
||||
Status: "500 Internal Server Error",
|
||||
StatusCode: http.StatusInternalServerError,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
ContentLength: int64(len(m.Body)),
|
||||
}
|
||||
|
||||
for k, v := range m.Header {
|
||||
rsp.Header.Set(k, v)
|
||||
}
|
||||
|
||||
return rsp.Write(h.conn)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) recvHTTP1(msg *Message) error {
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return errors.Wrap(err, "failed to set deadline")
|
||||
}
|
||||
}
|
||||
|
||||
var req *http.Request
|
||||
|
||||
select {
|
||||
// get first request
|
||||
case req = <-h.ch:
|
||||
// read next request
|
||||
default:
|
||||
rr, err := http.ReadRequest(h.rw.Reader)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read request")
|
||||
}
|
||||
|
||||
req = rr
|
||||
}
|
||||
|
||||
// read body
|
||||
b, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read body")
|
||||
}
|
||||
|
||||
// set body
|
||||
if err := req.Body.Close(); err != nil {
|
||||
return errors.Wrap(err, "failed to close body")
|
||||
}
|
||||
|
||||
msg.Body = b
|
||||
|
||||
// set headers
|
||||
for k, v := range req.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
// return early early
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) recvHTTP2(msg *Message) error {
|
||||
// only process if the socket is open
|
||||
select {
|
||||
case <-h.closed:
|
||||
return io.EOF
|
||||
default:
|
||||
}
|
||||
|
||||
// read streaming body
|
||||
|
||||
// set max buffer size
|
||||
s := h.ht.opts.BuffSizeH2
|
||||
if s == 0 {
|
||||
s = DefaultBufSizeH2
|
||||
}
|
||||
|
||||
buf := make([]byte, s)
|
||||
|
||||
// read the request body
|
||||
n, err := h.buf.Read(buf)
|
||||
// not an eof error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check if we have data
|
||||
if n > 0 {
|
||||
msg.Body = buf[:n]
|
||||
}
|
||||
|
||||
// set headers
|
||||
for k, v := range h.r.Header {
|
||||
if len(v) > 0 {
|
||||
msg.Header[k] = v[0]
|
||||
} else {
|
||||
msg.Header[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
// set path
|
||||
msg.Header[":path"] = h.r.URL.Path
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) sendHTTP1(msg *Message) error {
|
||||
// make copy of header
|
||||
hdr := make(http.Header)
|
||||
for k, v := range h.r.Header {
|
||||
hdr[k] = v
|
||||
}
|
||||
|
||||
rsp := &http.Response{
|
||||
Header: hdr,
|
||||
Body: io.NopCloser(bytes.NewReader(msg.Body)),
|
||||
Status: "200 OK",
|
||||
StatusCode: http.StatusOK,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
ContentLength: int64(len(msg.Body)),
|
||||
}
|
||||
|
||||
for k, v := range msg.Header {
|
||||
rsp.Header.Set(k, v)
|
||||
}
|
||||
|
||||
// set timeout if its greater than 0
|
||||
if h.ht.opts.Timeout > time.Duration(0) {
|
||||
if err := h.conn.SetDeadline(time.Now().Add(h.ht.opts.Timeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return rsp.Write(h.conn)
|
||||
}
|
||||
|
||||
func (h *httpTransportSocket) sendHTTP2(msg *Message) error {
|
||||
// only process if the socket is open
|
||||
select {
|
||||
case <-h.closed:
|
||||
return io.EOF
|
||||
default:
|
||||
}
|
||||
|
||||
// set headers
|
||||
for k, v := range msg.Header {
|
||||
h.w.Header().Set(k, v)
|
||||
}
|
||||
|
||||
// write request
|
||||
_, err := h.w.Write(msg.Body)
|
||||
|
||||
// flush the trailers
|
||||
h.w.(http.Flusher).Flush()
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"go-micro.dev/v4/logger"
|
||||
maddr "go-micro.dev/v4/util/addr"
|
||||
mnet "go-micro.dev/v4/util/net"
|
||||
mls "go-micro.dev/v4/util/tls"
|
||||
)
|
||||
|
||||
type httpTransport struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
func NewHTTPTransport(opts ...Option) *httpTransport {
|
||||
options := Options{
|
||||
BuffSizeH2: DefaultBufSizeH2,
|
||||
Logger: logger.DefaultLogger,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return &httpTransport{opts: options}
|
||||
}
|
||||
|
||||
func (h *httpTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&h.opts)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Dial(addr string, opts ...DialOption) (Client, error) {
|
||||
dopts := DialOptions{
|
||||
Timeout: DefaultDialTimeout,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&dopts)
|
||||
}
|
||||
|
||||
var (
|
||||
conn net.Conn
|
||||
err error
|
||||
)
|
||||
|
||||
if h.opts.Secure || h.opts.TLSConfig != nil {
|
||||
config := h.opts.TLSConfig
|
||||
if config == nil {
|
||||
config = &tls.Config{
|
||||
InsecureSkipVerify: dopts.InsecureSkipVerify,
|
||||
}
|
||||
}
|
||||
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
|
||||
conn, err = newConn(func(addr string) (net.Conn, error) {
|
||||
return tls.DialWithDialer(&net.Dialer{Timeout: dopts.Timeout}, "tcp", addr, config)
|
||||
})(addr)
|
||||
} else {
|
||||
conn, err = newConn(func(addr string) (net.Conn, error) {
|
||||
return net.DialTimeout("tcp", addr, dopts.Timeout)
|
||||
})(addr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &httpTransportClient{
|
||||
ht: h,
|
||||
addr: addr,
|
||||
conn: conn,
|
||||
buff: bufio.NewReader(conn),
|
||||
dialOpts: dopts,
|
||||
req: make(chan *http.Request, 100),
|
||||
local: conn.LocalAddr().String(),
|
||||
remote: conn.RemoteAddr().String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Listen(addr string, opts ...ListenOption) (Listener, error) {
|
||||
var options ListenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
var (
|
||||
list net.Listener
|
||||
err error
|
||||
)
|
||||
|
||||
switch listener := getNetListener(&options); {
|
||||
// Extracted listener from context
|
||||
case listener != nil:
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
|
||||
// Needs to create self signed certificate
|
||||
case h.opts.Secure || h.opts.TLSConfig != nil:
|
||||
config := h.opts.TLSConfig
|
||||
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
if config != nil {
|
||||
return tls.Listen("tcp", addr, config)
|
||||
}
|
||||
|
||||
hosts := []string{addr}
|
||||
|
||||
// check if its a valid host:port
|
||||
if host, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if len(host) == 0 {
|
||||
hosts = maddr.IPs()
|
||||
} else {
|
||||
hosts = []string{host}
|
||||
}
|
||||
}
|
||||
|
||||
// generate a certificate
|
||||
cert, err := mls.Certificate(hosts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config = &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
return tls.Listen("tcp", addr, config)
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
|
||||
// Create new basic net listener
|
||||
default:
|
||||
getList := func(addr string) (net.Listener, error) {
|
||||
return net.Listen("tcp", addr)
|
||||
}
|
||||
|
||||
list, err = mnet.Listen(addr, getList)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &httpTransportListener{
|
||||
ht: h,
|
||||
listener: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *httpTransport) Options() Options {
|
||||
return h.opts
|
||||
}
|
||||
|
||||
func (h *httpTransport) String() string {
|
||||
return "http"
|
||||
}
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
maddr "go-micro.dev/v4/util/addr"
|
||||
mnet "go-micro.dev/v4/util/net"
|
||||
)
|
||||
|
||||
type memorySocket struct {
|
||||
ctx context.Context
|
||||
// Client receiver of io.Pipe with gob
|
||||
crecv *gob.Decoder
|
||||
// Client sender of the io.Pipe with gob
|
||||
csend *gob.Encoder
|
||||
// Server receiver of the io.Pip with gob
|
||||
srecv *gob.Decoder
|
||||
// Server sender of the io.Pip with gob
|
||||
ssend *gob.Encoder
|
||||
// sock exit
|
||||
exit chan bool
|
||||
// listener exit
|
||||
lexit chan bool
|
||||
|
||||
local string
|
||||
remote string
|
||||
|
||||
// for send/recv Timeout
|
||||
timeout time.Duration
|
||||
// True server mode, False client mode
|
||||
server bool
|
||||
}
|
||||
|
||||
type memoryClient struct {
|
||||
*memorySocket
|
||||
opts DialOptions
|
||||
}
|
||||
|
||||
type memoryListener struct {
|
||||
lopts ListenOptions
|
||||
ctx context.Context
|
||||
exit chan bool
|
||||
conn chan *memorySocket
|
||||
topts Options
|
||||
addr string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type memoryTransport struct {
|
||||
listeners map[string]*memoryListener
|
||||
opts Options
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Recv(m *Message) error {
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
// connection closed
|
||||
return io.EOF
|
||||
case <-ms.lexit:
|
||||
// Server connection closed
|
||||
return io.EOF
|
||||
default:
|
||||
if ms.server {
|
||||
if err := ms.srecv.Decode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := ms.crecv.Decode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Local() string {
|
||||
return ms.local
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Remote() string {
|
||||
return ms.remote
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Send(m *Message) error {
|
||||
ctx := ms.ctx
|
||||
if ms.timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ms.ctx, ms.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ms.exit:
|
||||
// connection closed
|
||||
return io.EOF
|
||||
case <-ms.lexit:
|
||||
// Server connection closed
|
||||
return io.EOF
|
||||
default:
|
||||
if ms.server {
|
||||
if err := ms.ssend.Encode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := ms.csend.Encode(m); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *memorySocket) Close() error {
|
||||
select {
|
||||
case <-ms.exit:
|
||||
return nil
|
||||
default:
|
||||
close(ms.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Addr() string {
|
||||
return m.addr
|
||||
}
|
||||
|
||||
func (m *memoryListener) Close() error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
default:
|
||||
close(m.exit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryListener) Accept(fn func(Socket)) error {
|
||||
for {
|
||||
select {
|
||||
case <-m.exit:
|
||||
return nil
|
||||
case c := <-m.conn:
|
||||
go fn(&memorySocket{
|
||||
server: true,
|
||||
lexit: c.lexit,
|
||||
exit: c.exit,
|
||||
ssend: c.ssend,
|
||||
srecv: c.srecv,
|
||||
local: c.Remote(),
|
||||
remote: c.Local(),
|
||||
timeout: m.topts.Timeout,
|
||||
ctx: m.topts.Context,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Dial(addr string, opts ...DialOption) (Client, error) {
|
||||
m.RLock()
|
||||
defer m.RUnlock()
|
||||
|
||||
listener, ok := m.listeners[addr]
|
||||
if !ok {
|
||||
return nil, errors.New("could not dial " + addr)
|
||||
}
|
||||
|
||||
var options DialOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
creader, swriter := io.Pipe()
|
||||
sreader, cwriter := io.Pipe()
|
||||
|
||||
client := &memoryClient{
|
||||
&memorySocket{
|
||||
server: false,
|
||||
csend: gob.NewEncoder(cwriter),
|
||||
crecv: gob.NewDecoder(creader),
|
||||
ssend: gob.NewEncoder(swriter),
|
||||
srecv: gob.NewDecoder(sreader), exit: make(chan bool),
|
||||
lexit: listener.exit,
|
||||
local: addr,
|
||||
remote: addr,
|
||||
timeout: m.opts.Timeout,
|
||||
ctx: m.opts.Context,
|
||||
},
|
||||
options,
|
||||
}
|
||||
|
||||
// pseudo connect
|
||||
select {
|
||||
case <-listener.exit:
|
||||
return nil, errors.New("connection error")
|
||||
case listener.conn <- client.memorySocket:
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Listen(addr string, opts ...ListenOption) (Listener, error) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
var options ListenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addr, err = maddr.Extract(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// if zero port then randomly assign one
|
||||
if len(port) > 0 && port == "0" {
|
||||
i := rand.Intn(20000)
|
||||
port = fmt.Sprintf("%d", 10000+i)
|
||||
}
|
||||
|
||||
// set addr with port
|
||||
addr = mnet.HostPort(addr, port)
|
||||
|
||||
if _, ok := m.listeners[addr]; ok {
|
||||
return nil, errors.New("already listening on " + addr)
|
||||
}
|
||||
|
||||
listener := &memoryListener{
|
||||
lopts: options,
|
||||
topts: m.opts,
|
||||
addr: addr,
|
||||
conn: make(chan *memorySocket),
|
||||
exit: make(chan bool),
|
||||
ctx: m.opts.Context,
|
||||
}
|
||||
|
||||
m.listeners[addr] = listener
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Init(opts ...Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryTransport) Options() Options {
|
||||
return m.opts
|
||||
}
|
||||
|
||||
func (m *memoryTransport) String() string {
|
||||
return "memory"
|
||||
}
|
||||
|
||||
func NewMemoryTransport(opts ...Option) Transport {
|
||||
var options Options
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
if options.Context == nil {
|
||||
options.Context = context.Background()
|
||||
}
|
||||
|
||||
return &memoryTransport{
|
||||
opts: options,
|
||||
listeners: make(map[string]*memoryListener),
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v4/codec"
|
||||
"go-micro.dev/v4/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultBufSizeH2 = 4 * 1024 * 1024
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
// Codec is the codec interface to use where headers are not supported
|
||||
// by the transport and the entire payload must be encoded
|
||||
Codec codec.Marshaler
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
// Logger is the underline logger
|
||||
Logger logger.Logger
|
||||
// TLSConfig to secure the connection. The assumption is that this
|
||||
// is mTLS keypair
|
||||
TLSConfig *tls.Config
|
||||
// Addrs is the list of intermediary addresses to connect to
|
||||
Addrs []string
|
||||
// Timeout sets the timeout for Send/Recv
|
||||
Timeout time.Duration
|
||||
// BuffSizeH2 is the HTTP2 buffer size
|
||||
BuffSizeH2 int
|
||||
// Secure tells the transport to secure the connection.
|
||||
// In the case TLSConfig is not specified best effort self-signed
|
||||
// certs should be used
|
||||
Secure bool
|
||||
}
|
||||
|
||||
type DialOptions struct {
|
||||
|
||||
// TODO: add tls options when dialing
|
||||
// Currently set in global options
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
// Timeout for dialing
|
||||
Timeout time.Duration
|
||||
// Tells the transport this is a streaming connection with
|
||||
// multiple calls to send/recv and that send may not even be called
|
||||
Stream bool
|
||||
// ConnClose sets the Connection header to close
|
||||
ConnClose bool
|
||||
// InsecureSkipVerify skip TLS verification.
|
||||
InsecureSkipVerify bool
|
||||
}
|
||||
|
||||
type ListenOptions struct {
|
||||
// TODO: add tls options when listening
|
||||
// Currently set in global options
|
||||
|
||||
// Other options for implementations of the interface
|
||||
// can be stored in a context
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
// Addrs to use for transport.
|
||||
func Addrs(addrs ...string) Option {
|
||||
return func(o *Options) {
|
||||
o.Addrs = addrs
|
||||
}
|
||||
}
|
||||
|
||||
// Codec sets the codec used for encoding where the transport
|
||||
// does not support message headers.
|
||||
func Codec(c codec.Marshaler) Option {
|
||||
return func(o *Options) {
|
||||
o.Codec = c
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout sets the timeout for Send/Recv execution.
|
||||
func Timeout(t time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.Timeout = t
|
||||
}
|
||||
}
|
||||
|
||||
// Use secure communication. If TLSConfig is not specified we
|
||||
// use InsecureSkipVerify and generate a self signed cert.
|
||||
func Secure(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.Secure = b
|
||||
}
|
||||
}
|
||||
|
||||
// TLSConfig to be used for the transport.
|
||||
func TLSConfig(t *tls.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.TLSConfig = t
|
||||
}
|
||||
}
|
||||
|
||||
// Indicates whether this is a streaming connection.
|
||||
func WithStream() DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.Stream = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithTimeout(d time.Duration) DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.Timeout = d
|
||||
}
|
||||
}
|
||||
|
||||
// WithConnClose sets the Connection header to close.
|
||||
func WithConnClose() DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.ConnClose = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithInsecureSkipVerify(b bool) DialOption {
|
||||
return func(o *DialOptions) {
|
||||
o.InsecureSkipVerify = b
|
||||
}
|
||||
}
|
||||
|
||||
// Logger sets the underline logger.
|
||||
func Logger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// BuffSizeH2 sets the HTTP2 buffer size.
|
||||
// Default is 4 * 1024 * 1024.
|
||||
func BuffSizeH2(size int) Option {
|
||||
return func(o *Options) {
|
||||
o.BuffSizeH2 = size
|
||||
}
|
||||
}
|
||||
|
||||
// InsecureSkipVerify sets the TLS options to skip verification.
|
||||
// NetListener Set net.Listener for httpTransport.
|
||||
func NetListener(customListener net.Listener) ListenOption {
|
||||
return func(o *ListenOptions) {
|
||||
if customListener == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if o.Context == nil {
|
||||
o.Context = context.TODO()
|
||||
}
|
||||
|
||||
o.Context = context.WithValue(o.Context, netListener{}, customListener)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package transport is an interface for synchronous connection based communication
|
||||
package transport
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Transport is an interface which is used for communication between
|
||||
// services. It uses connection based socket send/recv semantics and
|
||||
// has various implementations; http, grpc, quic.
|
||||
type Transport interface {
|
||||
Init(...Option) error
|
||||
Options() Options
|
||||
Dial(addr string, opts ...DialOption) (Client, error)
|
||||
Listen(addr string, opts ...ListenOption) (Listener, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
// Message is a broker message.
|
||||
type Message struct {
|
||||
Header map[string]string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
type Socket interface {
|
||||
Recv(*Message) error
|
||||
Send(*Message) error
|
||||
Close() error
|
||||
Local() string
|
||||
Remote() string
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
Socket
|
||||
}
|
||||
|
||||
type Listener interface {
|
||||
Addr() string
|
||||
Close() error
|
||||
Accept(func(Socket)) error
|
||||
}
|
||||
|
||||
type Option func(*Options)
|
||||
|
||||
type DialOption func(*DialOptions)
|
||||
|
||||
type ListenOption func(*ListenOptions)
|
||||
|
||||
var (
|
||||
DefaultTransport Transport = NewHTTPTransport()
|
||||
|
||||
DefaultDialTimeout = time.Second * 5
|
||||
)
|
||||
Reference in New Issue
Block a user