feat: implement http support

Signed-off-by: Kairee Wu <kaireewu@gmail.com>
This commit is contained in:
2022-04-23 17:34:50 +08:00
parent 74ef998a9b
commit 4477a63c49
6 changed files with 150 additions and 4 deletions

View File

@ -1,6 +1,7 @@
package krpc
import (
"bufio"
"context"
"encoding/json"
"errors"
@ -8,6 +9,8 @@ import (
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
@ -241,3 +244,34 @@ func dialTimeout(f newClientFunc, network, address string,
return result.client, result.err
}
}
func NewHTTPClient(conn net.Conn, opts ...Option) (*Client, error) {
_, _ = fmt.Fprintf(conn,
"CONNECT %s HTTP/1.0\n\n", defaultRPCPath)
resp, err := http.ReadResponse(bufio.NewReader(conn),
&http.Request{Method: http.MethodConnect})
if err == nil && resp.Status == connected {
return NewClient(conn, opts...)
}
return nil, err
}
func DialHTTP(network, address string, opts ...Option) (*Client, error) {
return dialTimeout(NewHTTPClient, network, address, opts...)
}
func XDial(rpcAddr string, opts ...Option) (*Client, error) {
parts := strings.Split(rpcAddr, "://")
if len(parts) != 2 {
return nil, fmt.Errorf("rpc: client wrong format '%s', expect protocol://addr", rpcAddr)
}
protocol, addr := parts[0], parts[1]
switch protocol {
case "http":
return DialHTTP("tcp", addr, opts...)
default:
return Dial(protocol, addr, opts...)
}
}