Compare commits

...

10 Commits

@ -2,7 +2,9 @@ package starnet
import ( import (
"bytes" "bytes"
"context"
"crypto/rand" "crypto/rand"
"crypto/tls"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -20,6 +22,7 @@ const (
HEADER_FORM_URLENCODE = `application/x-www-form-urlencoded` HEADER_FORM_URLENCODE = `application/x-www-form-urlencoded`
HEADER_FORM_DATA = `multipart/form-data` HEADER_FORM_DATA = `multipart/form-data`
HEADER_JSON = `application/json` HEADER_JSON = `application/json`
HEADER_PLAIN = `text/plain`
) )
type RequestFile struct { type RequestFile struct {
@ -27,41 +30,205 @@ type RequestFile struct {
UploadForm map[string]string UploadForm map[string]string
UploadName string UploadName string
} }
type Request struct { type Request struct {
TimeOut int
DialTimeOut int
Url string Url string
RespURL string
Method string Method string
RecvData []byte RecvData []byte
RecvContentLength int64 RecvContentLength int64
WriteRecvData bool
RecvIo io.Writer RecvIo io.Writer
ReqHeader http.Header
ReqCookies []*http.Cookie
RespHeader http.Header RespHeader http.Header
RespCookies []*http.Cookie RespCookies []*http.Cookie
RespHttpCode int
Location *url.URL
CircleBuffer *stario.StarBuffer
respReader io.ReadCloser
respOrigin *http.Response
reqOrigin *http.Request
RequestOpts
}
type RequestOpts struct {
RequestFile RequestFile
RespHttpCode int PostBuffer io.Reader
PostBuffer *bytes.Buffer Process func(float64)
CircleBuffer *stario.StarBuffer Proxy string
Proxy string Timeout time.Duration
Process func(float64) DialTimeout time.Duration
ReqHeader http.Header
ReqCookies []*http.Cookie
WriteRecvData bool
SkipTLSVerify bool
CustomTransport *http.Transport
Queries map[string]string
DisableRedirect bool
TlsConfig *tls.Config
}
type RequestOpt func(opt *RequestOpts)
func WithDialTimeout(timeout time.Duration) RequestOpt {
return func(opt *RequestOpts) {
opt.DialTimeout = timeout
}
}
func WithTimeout(timeout time.Duration) RequestOpt {
return func(opt *RequestOpts) {
opt.Timeout = timeout
}
}
func WithHeader(key, val string) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqHeader.Set(key, val)
}
}
func WithTlsConfig(tlscfg *tls.Config) RequestOpt {
return func(opt *RequestOpts) {
opt.TlsConfig = tlscfg
}
}
func WithHeaderMap(header map[string]string) RequestOpt {
return func(opt *RequestOpts) {
for key, val := range header {
opt.ReqHeader.Set(key, val)
}
}
}
func WithHeaderAdd(key, val string) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqHeader.Add(key, val)
}
}
func WithReader(r io.Reader) RequestOpt {
return func(opt *RequestOpts) {
opt.PostBuffer = r
}
}
func WithFetchRespBody(fetch bool) RequestOpt {
return func(opt *RequestOpts) {
opt.WriteRecvData = fetch
}
}
func WithCookies(ck []*http.Cookie) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqCookies = ck
}
}
func WithCookie(key, val, path string) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqCookies = append(opt.ReqCookies, &http.Cookie{Name: key, Value: val, Path: path})
}
}
func WithCookieMap(header map[string]string, path string) RequestOpt {
return func(opt *RequestOpts) {
for key, val := range header {
opt.ReqCookies = append(opt.ReqCookies, &http.Cookie{Name: key, Value: val, Path: path})
}
}
}
func WithQueries(queries map[string]string) RequestOpt {
return func(opt *RequestOpts) {
opt.Queries = queries
}
}
func WithProxy(proxy string) RequestOpt {
return func(opt *RequestOpts) {
opt.Proxy = proxy
}
}
func WithProcess(fn func(float64)) RequestOpt {
return func(opt *RequestOpts) {
opt.Process = fn
}
}
func WithContentType(ct string) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqHeader.Set("Content-Type", ct)
}
}
func WithUserAgent(ua string) RequestOpt {
return func(opt *RequestOpts) {
opt.ReqHeader.Set("User-Agent", ua)
}
}
func WithCustomTransport(hs *http.Transport) RequestOpt {
return func(opt *RequestOpts) {
opt.CustomTransport = hs
}
}
func WithSkipTLSVerify(skip bool) RequestOpt {
return func(opt *RequestOpts) {
opt.SkipTLSVerify = skip
}
}
func WithDisableRedirect(disable bool) RequestOpt {
return func(opt *RequestOpts) {
opt.DisableRedirect = disable
}
} }
func NewRequests(url string, postdata []byte, method string) Request { func NewRequests(url string, rawdata []byte, method string, opts ...RequestOpt) Request {
req := Request{ req := Request{
TimeOut: 30, RequestOpts: RequestOpts{
DialTimeOut: 15, Timeout: 30 * time.Second,
Url: url, DialTimeout: 15 * time.Second,
PostBuffer: bytes.NewBuffer(postdata), WriteRecvData: true,
Method: method, },
WriteRecvData: true, Url: url,
Method: method,
}
if rawdata != nil {
req.PostBuffer = bytes.NewBuffer(rawdata)
} }
req.ReqHeader = make(http.Header) req.ReqHeader = make(http.Header)
if strings.ToUpper(method) == "POST" { if strings.ToUpper(method) == "POST" {
req.ReqHeader.Set("Content-Type", HEADER_FORM_URLENCODE) req.ReqHeader.Set("Content-Type", HEADER_FORM_URLENCODE)
} }
req.ReqHeader.Set("User-Agent", "B612 / 1.0.0") req.ReqHeader.Set("User-Agent", "B612 / 1.1.0")
for _, v := range opts {
v(&req.RequestOpts)
}
if req.CustomTransport == nil {
req.CustomTransport = &http.Transport{}
}
if req.SkipTLSVerify {
if req.CustomTransport.TLSClientConfig == nil {
req.CustomTransport.TLSClientConfig = &tls.Config{}
}
req.CustomTransport.TLSClientConfig.InsecureSkipVerify = true
}
if req.TlsConfig != nil {
req.CustomTransport.TLSClientConfig = req.TlsConfig
}
req.CustomTransport.DialContext = func(ctx context.Context, netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, req.DialTimeout)
if err != nil {
return nil, err
}
if req.Timeout != 0 {
c.SetDeadline(time.Now().Add(req.Timeout))
}
return c, nil
}
return req return req
} }
@ -76,6 +243,9 @@ func (curl *Request) ResetReqCookies() {
func (curl *Request) AddSimpleCookie(key, value string) { func (curl *Request) AddSimpleCookie(key, value string) {
curl.ReqCookies = append(curl.ReqCookies, &http.Cookie{Name: key, Value: value, Path: "/"}) curl.ReqCookies = append(curl.ReqCookies, &http.Cookie{Name: key, Value: value, Path: "/"})
} }
func (curl *Request) AddCookie(key, value, path string) {
curl.ReqCookies = append(curl.ReqCookies, &http.Cookie{Name: key, Value: value, Path: path})
}
func randomBoundary() string { func randomBoundary() string {
var buf [30]byte var buf [30]byte
@ -140,13 +310,16 @@ func Curl(curl Request) (resps Request, err error) {
curl.CircleBuffer = fpdst curl.CircleBuffer = fpdst
curl.ReqHeader.Set("Content-Type", "multipart/form-data;boundary="+boundary) curl.ReqHeader.Set("Content-Type", "multipart/form-data;boundary="+boundary)
} }
resp, err := netcurl(curl) req, resp, err := netcurl(curl)
if err != nil { if err != nil {
return Request{}, err return Request{}, err
} }
defer resp.Body.Close() if resp.Request != nil && resp.Request.URL != nil {
curl.PostBuffer = nil curl.RespURL = resp.Request.URL.String()
curl.CircleBuffer = nil }
curl.reqOrigin = req
curl.respOrigin = resp
curl.Location, _ = resp.Location()
curl.RespHttpCode = resp.StatusCode curl.RespHttpCode = resp.StatusCode
curl.RespHeader = resp.Header curl.RespHeader = resp.Header
curl.RespCookies = resp.Cookies() curl.RespCookies = resp.Cookies()
@ -182,6 +355,8 @@ func Curl(curl Request) (resps Request, err error) {
return return
} }
curl.RecvData = buf.Bytes() curl.RecvData = buf.Bytes()
} else {
curl.respReader = resp.Body
} }
if curl.RecvIo != nil { if curl.RecvIo != nil {
if curl.WriteRecvData { if curl.WriteRecvData {
@ -196,21 +371,33 @@ func Curl(curl Request) (resps Request, err error) {
return curl, err return curl, err
} }
func netcurl(curl Request) (*http.Response, error) { // RespBodyReader Only works when WriteRecvData set to false
func (curl *Request) RespBodyReader() io.ReadCloser {
return curl.respReader
}
func netcurl(curl Request) (*http.Request, *http.Response, error) {
var req *http.Request var req *http.Request
var err error var err error
if curl.Method == "" { if curl.Method == "" {
return nil, errors.New("Error Method Not Entered") return nil, nil, errors.New("Error Method Not Entered")
} }
if curl.PostBuffer != nil && curl.PostBuffer.Len() > 0 { if curl.PostBuffer != nil {
req, err = http.NewRequest(curl.Method, curl.Url, curl.PostBuffer) req, err = http.NewRequest(curl.Method, curl.Url, curl.PostBuffer)
} else if curl.CircleBuffer != nil && curl.CircleBuffer.Len() > 0 { } else if curl.CircleBuffer != nil && curl.CircleBuffer.Len() > 0 {
req, err = http.NewRequest(curl.Method, curl.Url, curl.CircleBuffer) req, err = http.NewRequest(curl.Method, curl.Url, curl.CircleBuffer)
} else { } else {
req, err = http.NewRequest(curl.Method, curl.Url, nil) req, err = http.NewRequest(curl.Method, curl.Url, nil)
} }
if curl.Queries != nil {
sid := req.URL.Query()
for k, v := range curl.Queries {
sid.Add(k, v)
}
req.URL.RawQuery = sid.Encode()
}
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
req.Header = curl.ReqHeader req.Header = curl.ReqHeader
if len(curl.ReqCookies) != 0 { if len(curl.ReqCookies) != 0 {
@ -218,31 +405,24 @@ func netcurl(curl Request) (*http.Response, error) {
req.AddCookie(v) req.AddCookie(v)
} }
} }
transport := &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
deadline := time.Now().Add(time.Duration(curl.TimeOut) * time.Second)
c, err := net.DialTimeout(netw, addr, time.Second*time.Duration(curl.DialTimeOut))
if err != nil {
return nil, err
}
if curl.TimeOut != 0 {
c.SetDeadline(deadline)
}
return c, nil
},
}
if curl.Proxy != "" { if curl.Proxy != "" {
purl, err := url.Parse(curl.Proxy) purl, err := url.Parse(curl.Proxy)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
transport.Proxy = http.ProxyURL(purl) curl.CustomTransport.Proxy = http.ProxyURL(purl)
} }
client := &http.Client{ client := &http.Client{
Transport: transport, Transport: curl.CustomTransport,
}
if curl.DisableRedirect {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
} }
resp, err := client.Do(req) resp, err := client.Do(req)
return resp, err
return req, resp, err
} }
func UrlEncodeRaw(str string) string { func UrlEncodeRaw(str string) string {
@ -258,10 +438,26 @@ func UrlDecode(str string) (string, error) {
return url.QueryUnescape(str) return url.QueryUnescape(str)
} }
func Build_Query(queryData map[string]string) string { func BuildQuery(queryData map[string]string) string {
query := url.Values{} query := url.Values{}
for k, v := range queryData { for k, v := range queryData {
query.Add(k, v) query.Add(k, v)
} }
return query.Encode() return query.Encode()
} }
func BuildPostForm(queryMap map[string]string) []byte {
query := url.Values{}
for k, v := range queryMap {
query.Add(k, v)
}
return []byte(query.Encode())
}
func (r Request) Resopnse() *http.Response {
return r.respOrigin
}
func (r Request) Request() *http.Request {
return r.reqOrigin
}

@ -0,0 +1,5 @@
module b612.me/starnet
go 1.16
require b612.me/stario v0.0.9

@ -0,0 +1,47 @@
b612.me/stario v0.0.9 h1:bFDlejUJMwZ12a09snZJspQsOlkqpDAl9qKPEYOGWCk=
b612.me/stario v0.0.9/go.mod h1:x4D/x8zA5SC0pj/uJAi4FyG5p4j5UZoMEZfvuRR6VNw=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

@ -33,6 +33,7 @@ func getICMP(seq uint16) ICMP {
func sendICMPRequest(icmp ICMP, destAddr *net.IPAddr, timeout time.Duration) (PingResult, error) { func sendICMPRequest(icmp ICMP, destAddr *net.IPAddr, timeout time.Duration) (PingResult, error) {
var res PingResult var res PingResult
res.RemoteIP = destAddr.String()
conn, err := net.DialIP("ip:icmp", nil, destAddr) conn, err := net.DialIP("ip:icmp", nil, destAddr)
if err != nil { if err != nil {
return res, err return res, err
@ -84,6 +85,7 @@ func checkSum(data []byte) uint16 {
type PingResult struct { type PingResult struct {
Duration time.Duration Duration time.Duration
RecvCount int RecvCount int
RemoteIP string
} }
func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) { func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) {
@ -95,3 +97,14 @@ func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) {
icmp := getICMP(uint16(seq)) icmp := getICMP(uint16(seq))
return sendICMPRequest(icmp, ipAddr, timeout) return sendICMPRequest(icmp, ipAddr, timeout)
} }
func IsIpPingable(ip string, timeout time.Duration, retryLimit int) bool {
for i := 0; i < retryLimit; i++ {
_, err := Ping(ip, 29, timeout)
if err != nil {
continue
}
return true
}
return false
}

@ -7,5 +7,9 @@ import (
) )
func Test_Ping(t *testing.T) { func Test_Ping(t *testing.T) {
fmt.Println(Ping("baidu.com", 0, time.Second*2)) fmt.Println(Ping("baidu.com", 29, time.Second*2))
fmt.Println(Ping("www.b612.me", 29, time.Second*2))
fmt.Println(IsIpPingable("baidu.com", time.Second*2, 3))
fmt.Println(IsIpPingable("www.b612.me", time.Second*2, 3))
} }

144
que.go

@ -5,11 +5,14 @@ import (
"context" "context"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt"
"os" "os"
"sync" "sync"
"time" "time"
) )
var ErrDeadlineExceeded error = errors.New("deadline exceeded")
// 识别头 // 识别头
var header = []byte{11, 27, 19, 96, 12, 25, 02, 20} var header = []byte{11, 27, 19, 96, 12, 25, 02, 20}
@ -22,13 +25,13 @@ type MsgQueue struct {
// StarQueue 为流数据中的消息队列分发 // StarQueue 为流数据中的消息队列分发
type StarQueue struct { type StarQueue struct {
maxLength uint32
count int64 count int64
Encode bool Encode bool
Reserve uint16 msgID uint16
Msgid uint16 msgPool chan MsgQueue
MsgPool chan MsgQueue unFinMsg sync.Map
UnFinMsg sync.Map lastID int //= -1
LastID int //= -1
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
duration time.Duration duration time.Duration
@ -37,21 +40,22 @@ type StarQueue struct {
//restoreMu sync.Mutex //restoreMu sync.Mutex
} }
func NewQueueCtx(ctx context.Context, count int64) *StarQueue { func NewQueueCtx(ctx context.Context, count int64, maxMsgLength uint32) *StarQueue {
var que StarQueue var q StarQueue
que.Encode = false q.Encode = false
que.count = count q.count = count
que.MsgPool = make(chan MsgQueue, count) q.maxLength = maxMsgLength
q.msgPool = make(chan MsgQueue, count)
if ctx == nil { if ctx == nil {
que.ctx, que.cancel = context.WithCancel(context.Background()) q.ctx, q.cancel = context.WithCancel(context.Background())
} else { } else {
que.ctx, que.cancel = context.WithCancel(ctx) q.ctx, q.cancel = context.WithCancel(ctx)
} }
que.duration = 0 q.duration = 0
return &que return &q
} }
func NewQueueWithCount(count int64) *StarQueue { func NewQueueWithCount(count int64) *StarQueue {
return NewQueueCtx(nil, count) return NewQueueCtx(nil, count, 0)
} }
// NewQueue 建立一个新消息队列 // NewQueue 建立一个新消息队列
@ -94,27 +98,27 @@ func ByteToUint16(src []byte) uint16 {
} }
// BuildMessage 生成编码后的信息用于发送 // BuildMessage 生成编码后的信息用于发送
func (que *StarQueue) BuildMessage(src []byte) []byte { func (q *StarQueue) BuildMessage(src []byte) []byte {
var buff bytes.Buffer var buff bytes.Buffer
que.Msgid++ q.msgID++
if que.Encode { if q.Encode {
src = que.EncodeFunc(src) src = q.EncodeFunc(src)
} }
length := uint32(len(src)) length := uint32(len(src))
buff.Write(header) buff.Write(header)
buff.Write(Uint32ToByte(length)) buff.Write(Uint32ToByte(length))
buff.Write(Uint16ToByte(que.Msgid)) buff.Write(Uint16ToByte(q.msgID))
buff.Write(src) buff.Write(src)
return buff.Bytes() return buff.Bytes()
} }
// BuildHeader 生成编码后的Header用于发送 // BuildHeader 生成编码后的Header用于发送
func (que *StarQueue) BuildHeader(length uint32) []byte { func (q *StarQueue) BuildHeader(length uint32) []byte {
var buff bytes.Buffer var buff bytes.Buffer
que.Msgid++ q.msgID++
buff.Write(header) buff.Write(header)
buff.Write(Uint32ToByte(length)) buff.Write(Uint32ToByte(length))
buff.Write(Uint16ToByte(que.Msgid)) buff.Write(Uint16ToByte(q.msgID))
return buff.Bytes() return buff.Bytes()
} }
@ -126,18 +130,18 @@ type unFinMsg struct {
RecvMsg []byte RecvMsg []byte
} }
func (que *StarQueue) push2list(msg MsgQueue) { func (q *StarQueue) push2list(msg MsgQueue) {
que.MsgPool <- msg q.msgPool <- msg
} }
// ParseMessage 用于解析收到的msg信息 // ParseMessage 用于解析收到的msg信息
func (que *StarQueue) ParseMessage(msg []byte, conn interface{}) error { func (q *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
// parseMessage 用于解析收到的msg信息 // parseMessage 用于解析收到的msg信息
func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error { func (q *StarQueue) parseMessage(msg []byte, conn interface{}) error {
tmp, ok := que.UnFinMsg.Load(conn) tmp, ok := q.unFinMsg.Load(conn)
if ok { //存在未完成的信息 if ok { //存在未完成的信息
lastMsg := tmp.(*unFinMsg) lastMsg := tmp.(*unFinMsg)
headerLen := len(lastMsg.HeaderMsg) headerLen := len(lastMsg.HeaderMsg)
@ -146,7 +150,7 @@ func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error {
if len(msg) < 14-headerLen { if len(msg) < 14-headerLen {
//加入header头并退出 //加入header头并退出
lastMsg.HeaderMsg = bytesMerge(lastMsg.HeaderMsg, msg) lastMsg.HeaderMsg = bytesMerge(lastMsg.HeaderMsg, msg)
que.UnFinMsg.Store(conn, lastMsg) q.unFinMsg.Store(conn, lastMsg)
return nil return nil
} }
//获取14字节完整的header //获取14字节完整的header
@ -155,28 +159,32 @@ func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error {
//检查收到的header是否为认证header //检查收到的header是否为认证header
//若不是,丢弃并重新来过 //若不是,丢弃并重新来过
if !checkHeader(lastMsg.HeaderMsg[0:8]) { if !checkHeader(lastMsg.HeaderMsg[0:8]) {
que.UnFinMsg.Delete(conn) q.unFinMsg.Delete(conn)
if len(msg) == 0 { if len(msg) == 0 {
return nil return nil
} }
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
//获得本数据包长度 //获得本数据包长度
lastMsg.LengthRecv = ByteToUint32(lastMsg.HeaderMsg[8:12]) lastMsg.LengthRecv = ByteToUint32(lastMsg.HeaderMsg[8:12])
if q.maxLength != 0 && lastMsg.LengthRecv > q.maxLength {
q.unFinMsg.Delete(conn)
return fmt.Errorf("msg length is %d ,too large than %d", lastMsg.LengthRecv, q.maxLength)
}
//获得本数据包ID //获得本数据包ID
lastMsg.ID = ByteToUint16(lastMsg.HeaderMsg[12:14]) lastMsg.ID = ByteToUint16(lastMsg.HeaderMsg[12:14])
//存入列表 //存入列表
que.UnFinMsg.Store(conn, lastMsg) q.unFinMsg.Store(conn, lastMsg)
msg = msg[14-headerLen:] msg = msg[14-headerLen:]
if uint32(len(msg)) < lastMsg.LengthRecv { if uint32(len(msg)) < lastMsg.LengthRecv {
lastMsg.RecvMsg = msg lastMsg.RecvMsg = msg
que.UnFinMsg.Store(conn, lastMsg) q.unFinMsg.Store(conn, lastMsg)
return nil return nil
} }
if uint32(len(msg)) >= lastMsg.LengthRecv { if uint32(len(msg)) >= lastMsg.LengthRecv {
lastMsg.RecvMsg = msg[0:lastMsg.LengthRecv] lastMsg.RecvMsg = msg[0:lastMsg.LengthRecv]
if que.Encode { if q.Encode {
lastMsg.RecvMsg = que.DecodeFunc(lastMsg.RecvMsg) lastMsg.RecvMsg = q.DecodeFunc(lastMsg.RecvMsg)
} }
msg = msg[lastMsg.LengthRecv:] msg = msg[lastMsg.LengthRecv:]
storeMsg := MsgQueue{ storeMsg := MsgQueue{
@ -184,38 +192,38 @@ func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error {
Msg: lastMsg.RecvMsg, Msg: lastMsg.RecvMsg,
Conn: conn, Conn: conn,
} }
//que.restoreMu.Lock() //q.restoreMu.Lock()
que.push2list(storeMsg) q.push2list(storeMsg)
//que.restoreMu.Unlock() //q.restoreMu.Unlock()
que.UnFinMsg.Delete(conn) q.unFinMsg.Delete(conn)
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
} else { } else {
lastID := int(lastMsg.LengthRecv) - len(lastMsg.RecvMsg) lastID := int(lastMsg.LengthRecv) - len(lastMsg.RecvMsg)
if lastID < 0 { if lastID < 0 {
que.UnFinMsg.Delete(conn) q.unFinMsg.Delete(conn)
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
if len(msg) >= lastID { if len(msg) >= lastID {
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg[0:lastID]) lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg[0:lastID])
if que.Encode { if q.Encode {
lastMsg.RecvMsg = que.DecodeFunc(lastMsg.RecvMsg) lastMsg.RecvMsg = q.DecodeFunc(lastMsg.RecvMsg)
} }
storeMsg := MsgQueue{ storeMsg := MsgQueue{
ID: lastMsg.ID, ID: lastMsg.ID,
Msg: lastMsg.RecvMsg, Msg: lastMsg.RecvMsg,
Conn: conn, Conn: conn,
} }
que.push2list(storeMsg) q.push2list(storeMsg)
que.UnFinMsg.Delete(conn) q.unFinMsg.Delete(conn)
if len(msg) == lastID { if len(msg) == lastID {
return nil return nil
} }
msg = msg[lastID:] msg = msg[lastID:]
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg) lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg)
que.UnFinMsg.Store(conn, lastMsg) q.unFinMsg.Store(conn, lastMsg)
return nil return nil
} }
} }
@ -228,8 +236,8 @@ func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error {
} }
msg = msg[start:] msg = msg[start:]
lastMsg := unFinMsg{} lastMsg := unFinMsg{}
que.UnFinMsg.Store(conn, &lastMsg) q.unFinMsg.Store(conn, &lastMsg)
return que.parseMessage(msg, conn) return q.parseMessage(msg, conn)
} }
func checkHeader(msg []byte) bool { func checkHeader(msg []byte) bool {
@ -275,19 +283,19 @@ func bytesMerge(src ...[]byte) []byte {
} }
// Restore 获取收到的信息 // Restore 获取收到的信息
func (que *StarQueue) Restore() (MsgQueue, error) { func (q *StarQueue) Restore() (MsgQueue, error) {
if que.duration.Seconds() == 0 { if q.duration.Seconds() == 0 {
que.duration = 86400 * time.Second q.duration = 86400 * time.Second
} }
for { for {
select { select {
case <-que.ctx.Done(): case <-q.ctx.Done():
return MsgQueue{}, errors.New("Stoped By External Function Call") return MsgQueue{}, errors.New("Stoped By External Function Call")
case <-time.After(que.duration): case <-time.After(q.duration):
if que.duration != 0 { if q.duration != 0 {
return MsgQueue{}, os.ErrDeadlineExceeded return MsgQueue{}, ErrDeadlineExceeded
} }
case data, ok := <-que.MsgPool: case data, ok := <-q.msgPool:
if !ok { if !ok {
return MsgQueue{}, os.ErrClosed return MsgQueue{}, os.ErrClosed
} }
@ -297,21 +305,21 @@ func (que *StarQueue) Restore() (MsgQueue, error) {
} }
// RestoreOne 获取收到的一个信息 // RestoreOne 获取收到的一个信息
//兼容性修改 // 兼容性修改
func (que *StarQueue) RestoreOne() (MsgQueue, error) { func (q *StarQueue) RestoreOne() (MsgQueue, error) {
return que.Restore() return q.Restore()
} }
// Stop 立即停止Restore // Stop 立即停止Restore
func (que *StarQueue) Stop() { func (q *StarQueue) Stop() {
que.cancel() q.cancel()
} }
// RestoreDuration Restore最大超时时间 // RestoreDuration Restore最大超时时间
func (que *StarQueue) RestoreDuration(tm time.Duration) { func (q *StarQueue) RestoreDuration(tm time.Duration) {
que.duration = tm q.duration = tm
} }
func (que *StarQueue) RestoreChan() <-chan MsgQueue { func (q *StarQueue) RestoreChan() <-chan MsgQueue {
return que.MsgPool return q.msgPool
} }

Loading…
Cancel
Save