feat: implement http support
Signed-off-by: Kairee Wu <kaireewu@gmail.com>
This commit is contained in:
34
client.go
34
client.go
@ -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...)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user