GO-RPC HTTP带token客户端

  • A+
所属分类:阁主小札
package utils

import (
	"bufio"
	"errors"
	"net"
	"net/http"
	"net/rpc"
	"time"
)

var (
	connected = "200 Connected to Go RPC"
	//ErrUnauthorized 401 缺少token或token无效
	ErrUnauthorized = errors.New("401 缺少token或token无效")
)

//NewClient 新建RPC客户端
func NewClient(address, path, token string, timeout time.Duration) (*rpc.Client, error) {
	client := &rpc.Client{}
	//连接
	conn, err := net.DialTimeout("tcp", address, timeout)
	if err != nil {
		return client, err
	}
	//写入头
	_, err = conn.Write([]byte("CONNECT " + path + " HTTP/1.1\r\nToken:" + token + "\r\n\r\n"))
	if err != nil {
		return client, err
	}
	//判断响应
	resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
	if err != nil {
		return client, err
	}
	if resp.Status != connected {
		if resp.StatusCode == 401 {
			return client, ErrUnauthorized
		}
		return client, errors.New("unexpected HTTP response: " + resp.Status)
	}
	//返回client
	return rpc.NewClient(conn), nil

}

weinxin
画麟阁QQ群
这是一个有爱的大家庭,也是东阁唯一的社区,快来和大家一起闲聊、讨论吧!
谷雨

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: