11 Commits

Author SHA1 Message Date
b612 319518d71d update go mod 2023-02-11 17:17:03 +08:00
b612 be3df9703e update go mod and improve icmp result 2023-02-11 17:15:01 +08:00
b612 b92288bbc9 update go mod 2023-02-03 13:18:53 +08:00
b612 0805549006 add origin request/response http method 2022-09-06 15:15:33 +08:00
b612 033272f38a add tls config 2022-08-22 16:22:22 +08:00
b612 93b756d9fb add no auto redirect config 2022-06-06 11:18:42 +08:00
b612 d71eacdc91 optional function add 2022-03-14 15:43:56 +08:00
b612 747fc52c44 go mod support 2022-03-14 11:03:42 +08:00
b612 ce3ebbbf8a add bodyreader fn 2022-03-11 09:29:09 +08:00
b612 66c8abbcea bug fix 2021-11-12 15:56:23 +08:00
Starainrt b4bffa978c add ping functions 2021-06-04 10:49:23 +08:00
7 changed files with 488 additions and 85 deletions
+241 -45
View File
@@ -2,7 +2,9 @@ package starnet
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"errors"
"fmt"
"io"
@@ -20,6 +22,7 @@ const (
HEADER_FORM_URLENCODE = `application/x-www-form-urlencoded`
HEADER_FORM_DATA = `multipart/form-data`
HEADER_JSON = `application/json`
HEADER_PLAIN = `text/plain`
)
type RequestFile struct {
@@ -27,41 +30,205 @@ type RequestFile struct {
UploadForm map[string]string
UploadName string
}
type Request struct {
TimeOut int
DialTimeOut int
Url string
RespURL string
Method string
RecvData []byte
RecvContentLength int64
WriteRecvData bool
RecvIo io.Writer
ReqHeader http.Header
ReqCookies []*http.Cookie
RespHeader http.Header
RespCookies []*http.Cookie
RequestFile
RespHttpCode int
PostBuffer *bytes.Buffer
CircleBuffer *stario.StarBuffer
Proxy string
Process func(float64)
RespHttpCode int
Location *url.URL
CircleBuffer *stario.StarBuffer
respReader io.ReadCloser
respOrigin *http.Response
reqOrigin *http.Request
RequestOpts
}
func NewRequests(url string, postdata []byte, method string) Request {
type RequestOpts struct {
RequestFile
PostBuffer io.Reader
Process func(float64)
Proxy string
Timeout time.Duration
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, rawdata []byte, method string, opts ...RequestOpt) Request {
req := Request{
TimeOut: 30,
DialTimeOut: 15,
Url: url,
PostBuffer: bytes.NewBuffer(postdata),
Method: method,
WriteRecvData: true,
RequestOpts: RequestOpts{
Timeout: 30 * time.Second,
DialTimeout: 15 * time.Second,
WriteRecvData: true,
},
Url: url,
Method: method,
}
if rawdata != nil {
req.PostBuffer = bytes.NewBuffer(rawdata)
}
req.ReqHeader = make(http.Header)
if strings.ToUpper(method) == "POST" {
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
}
@@ -76,6 +243,9 @@ func (curl *Request) ResetReqCookies() {
func (curl *Request) AddSimpleCookie(key, value string) {
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 {
var buf [30]byte
@@ -140,13 +310,16 @@ func Curl(curl Request) (resps Request, err error) {
curl.CircleBuffer = fpdst
curl.ReqHeader.Set("Content-Type", "multipart/form-data;boundary="+boundary)
}
resp, err := netcurl(curl)
req, resp, err := netcurl(curl)
if err != nil {
return Request{}, err
}
defer resp.Body.Close()
curl.PostBuffer = nil
curl.CircleBuffer = nil
if resp.Request != nil && resp.Request.URL != nil {
curl.RespURL = resp.Request.URL.String()
}
curl.reqOrigin = req
curl.respOrigin = resp
curl.Location, _ = resp.Location()
curl.RespHttpCode = resp.StatusCode
curl.RespHeader = resp.Header
curl.RespCookies = resp.Cookies()
@@ -182,6 +355,8 @@ func Curl(curl Request) (resps Request, err error) {
return
}
curl.RecvData = buf.Bytes()
} else {
curl.respReader = resp.Body
}
if curl.RecvIo != nil {
if curl.WriteRecvData {
@@ -196,21 +371,33 @@ func Curl(curl Request) (resps Request, err error) {
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 err error
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)
} else if curl.CircleBuffer != nil && curl.CircleBuffer.Len() > 0 {
req, err = http.NewRequest(curl.Method, curl.Url, curl.CircleBuffer)
} else {
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 {
return nil, err
return nil, nil, err
}
req.Header = curl.ReqHeader
if len(curl.ReqCookies) != 0 {
@@ -218,31 +405,24 @@ func netcurl(curl Request) (*http.Response, error) {
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 != "" {
purl, err := url.Parse(curl.Proxy)
if err != nil {
return nil, err
return nil, nil, err
}
transport.Proxy = http.ProxyURL(purl)
curl.CustomTransport.Proxy = http.ProxyURL(purl)
}
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)
return resp, err
return req, resp, err
}
func UrlEncodeRaw(str string) string {
@@ -258,10 +438,26 @@ func UrlDecode(str string) (string, error) {
return url.QueryUnescape(str)
}
func Build_Query(queryData map[string]string) string {
func BuildQuery(queryData map[string]string) string {
query := url.Values{}
for k, v := range queryData {
query.Add(k, v)
}
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
}
+5
View File
@@ -0,0 +1,5 @@
module b612.me/starnet
go 1.16
require b612.me/stario v0.0.8
+13
View File
@@ -0,0 +1,13 @@
b612.me/stario v0.0.8 h1:kaA4pszAKLZJm2D9JmiuYSpgjTeE3VaO74vm+H0vBGM=
b612.me/stario v0.0.8/go.mod h1:or4ssWcxQSjMeu+hRKEgtp0X517b3zdlEOAms8Qscvw=
golang.org/x/crypto v0.0.0-20220313003712-b769efc7c000 h1:SL+8VVnkqyshUSz5iNnXtrBQzvFF2SkROm6t5RczFAE=
golang.org/x/crypto v0.0.0-20220313003712-b769efc7c000/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+110
View File
@@ -0,0 +1,110 @@
package starnet
import (
"bytes"
"encoding/binary"
"net"
"time"
)
type ICMP struct {
Type uint8
Code uint8
CheckSum uint16
Identifier uint16
SequenceNum uint16
}
func getICMP(seq uint16) ICMP {
icmp := ICMP{
Type: 8,
Code: 0,
CheckSum: 0,
Identifier: 0,
SequenceNum: seq,
}
var buffer bytes.Buffer
binary.Write(&buffer, binary.BigEndian, icmp)
icmp.CheckSum = checkSum(buffer.Bytes())
buffer.Reset()
return icmp
}
func sendICMPRequest(icmp ICMP, destAddr *net.IPAddr, timeout time.Duration) (PingResult, error) {
var res PingResult
res.RemoteIP = destAddr.String()
conn, err := net.DialIP("ip:icmp", nil, destAddr)
if err != nil {
return res, err
}
defer conn.Close()
var buffer bytes.Buffer
binary.Write(&buffer, binary.BigEndian, icmp)
if _, err := conn.Write(buffer.Bytes()); err != nil {
return res, err
}
tStart := time.Now()
conn.SetReadDeadline((time.Now().Add(timeout)))
recv := make([]byte, 1024)
res.RecvCount, err = conn.Read(recv)
if err != nil {
return res, err
}
tEnd := time.Now()
res.Duration = tEnd.Sub(tStart)
return res, err
}
func checkSum(data []byte) uint16 {
var (
sum uint32
length int = len(data)
index int
)
for length > 1 {
sum += uint32(data[index])<<8 + uint32(data[index+1])
index += 2
length -= 2
}
if length > 0 {
sum += uint32(data[index])
}
sum += (sum >> 16)
return uint16(^sum)
}
type PingResult struct {
Duration time.Duration
RecvCount int
RemoteIP string
}
func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) {
var res PingResult
ipAddr, err := net.ResolveIPAddr("ip", ip)
if err != nil {
return res, err
}
icmp := getICMP(uint16(seq))
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
}
+15
View File
@@ -0,0 +1,15 @@
package starnet
import (
"fmt"
"testing"
"time"
)
func Test_Ping(t *testing.T) {
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))
}
+62 -40
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/binary"
"errors"
"os"
"sync"
"time"
)
@@ -21,10 +22,11 @@ type MsgQueue struct {
// StarQueue 为流数据中的消息队列分发
type StarQueue struct {
count int64
Encode bool
Reserve uint16
Msgid uint16
MsgPool []MsgQueue
MsgPool chan MsgQueue
UnFinMsg sync.Map
LastID int //= -1
ctx context.Context
@@ -32,17 +34,29 @@ type StarQueue struct {
duration time.Duration
EncodeFunc func([]byte) []byte
DecodeFunc func([]byte) []byte
//parseMu sync.Mutex
restoreMu sync.Mutex
//restoreMu sync.Mutex
}
func NewQueueCtx(ctx context.Context, count int64) *StarQueue {
var que StarQueue
que.Encode = false
que.count = count
que.MsgPool = make(chan MsgQueue, count)
if ctx == nil {
que.ctx, que.cancel = context.WithCancel(context.Background())
} else {
que.ctx, que.cancel = context.WithCancel(ctx)
}
que.duration = 0
return &que
}
func NewQueueWithCount(count int64) *StarQueue {
return NewQueueCtx(nil, count)
}
// NewQueue 建立一个新消息队列
func NewQueue() *StarQueue {
var que StarQueue
que.Encode = false
que.ctx, que.cancel = context.WithCancel(context.Background())
que.duration = 0
return &que
return NewQueueWithCount(32)
}
// Uint32ToByte 4位uint32转byte
@@ -112,8 +126,17 @@ type unFinMsg struct {
RecvMsg []byte
}
func (que *StarQueue) push2list(msg MsgQueue) {
que.MsgPool <- msg
}
// ParseMessage 用于解析收到的msg信息
func (que *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
return que.parseMessage(msg, conn)
}
// parseMessage 用于解析收到的msg信息
func (que *StarQueue) parseMessage(msg []byte, conn interface{}) error {
tmp, ok := que.UnFinMsg.Load(conn)
if ok { //存在未完成的信息
lastMsg := tmp.(*unFinMsg)
@@ -136,7 +159,7 @@ func (que *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
if len(msg) == 0 {
return nil
}
return que.ParseMessage(msg, conn)
return que.parseMessage(msg, conn)
}
//获得本数据包长度
lastMsg.LengthRecv = ByteToUint32(lastMsg.HeaderMsg[8:12])
@@ -156,38 +179,40 @@ func (que *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
lastMsg.RecvMsg = que.DecodeFunc(lastMsg.RecvMsg)
}
msg = msg[lastMsg.LengthRecv:]
stroeMsg := MsgQueue{
storeMsg := MsgQueue{
ID: lastMsg.ID,
Msg: lastMsg.RecvMsg,
Conn: conn,
}
que.MsgPool = append(que.MsgPool, stroeMsg)
//que.restoreMu.Lock()
que.push2list(storeMsg)
//que.restoreMu.Unlock()
que.UnFinMsg.Delete(conn)
return que.ParseMessage(msg, conn)
return que.parseMessage(msg, conn)
}
} else {
lastID := int(lastMsg.LengthRecv) - len(lastMsg.RecvMsg)
if lastID < 0 {
que.UnFinMsg.Delete(conn)
return que.ParseMessage(msg, conn)
return que.parseMessage(msg, conn)
}
if len(msg) >= lastID {
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg[0:lastID])
if que.Encode {
lastMsg.RecvMsg = que.DecodeFunc(lastMsg.RecvMsg)
}
stroeMsg := MsgQueue{
storeMsg := MsgQueue{
ID: lastMsg.ID,
Msg: lastMsg.RecvMsg,
Conn: conn,
}
que.MsgPool = append(que.MsgPool, stroeMsg)
que.push2list(storeMsg)
que.UnFinMsg.Delete(conn)
if len(msg) == lastID {
return nil
}
msg = msg[lastID:]
return que.ParseMessage(msg, conn)
return que.parseMessage(msg, conn)
}
lastMsg.RecvMsg = bytesMerge(lastMsg.RecvMsg, msg)
que.UnFinMsg.Store(conn, lastMsg)
@@ -204,7 +229,7 @@ func (que *StarQueue) ParseMessage(msg []byte, conn interface{}) error {
msg = msg[start:]
lastMsg := unFinMsg{}
que.UnFinMsg.Store(conn, &lastMsg)
return que.ParseMessage(msg, conn)
return que.parseMessage(msg, conn)
}
func checkHeader(msg []byte) bool {
@@ -250,38 +275,31 @@ func bytesMerge(src ...[]byte) []byte {
}
// Restore 获取收到的信息
func (que *StarQueue) Restore(n int) ([]MsgQueue, error) {
que.restoreMu.Lock()
defer que.restoreMu.Unlock()
var res []MsgQueue
dura := time.Duration(0)
for len(que.MsgPool) < n {
func (que *StarQueue) Restore() (MsgQueue, error) {
if que.duration.Seconds() == 0 {
que.duration = 86400 * time.Second
}
for {
select {
case <-que.ctx.Done():
return res, errors.New("Stoped By External Function Call")
default:
time.Sleep(time.Millisecond * 20)
dura = time.Millisecond*20 + dura
if que.duration != 0 && dura > que.duration {
return res, errors.New("Time Exceed")
return MsgQueue{}, errors.New("Stoped By External Function Call")
case <-time.After(que.duration):
if que.duration != 0 {
return MsgQueue{}, os.ErrDeadlineExceeded
}
case data, ok := <-que.MsgPool:
if !ok {
return MsgQueue{}, os.ErrClosed
}
return data, nil
}
}
if len(que.MsgPool) < n {
return res, errors.New("Result Not Enough")
}
res = que.MsgPool[0:n]
que.MsgPool = que.MsgPool[n:]
return res, nil
}
// RestoreOne 获取收到的一个信息
//兼容性修改
func (que *StarQueue) RestoreOne() (MsgQueue, error) {
data, err := que.Restore(1)
if len(data) == 1 {
return data[0], err
}
return MsgQueue{}, err
return que.Restore()
}
// Stop 立即停止Restore
@@ -293,3 +311,7 @@ func (que *StarQueue) Stop() {
func (que *StarQueue) RestoreDuration(tm time.Duration) {
que.duration = tm
}
func (que *StarQueue) RestoreChan() <-chan MsgQueue {
return que.MsgPool
}
+42
View File
@@ -0,0 +1,42 @@
package starnet
import (
"fmt"
"testing"
"time"
)
func Test_QueSpeed(t *testing.T) {
que := NewQueueWithCount(0)
stop := make(chan struct{}, 1)
que.RestoreDuration(time.Second * 10)
var count int64
go func() {
for {
select {
case <-stop:
//fmt.Println(count)
return
default:
}
_, err := que.RestoreOne()
if err == nil {
count++
}
}
}()
cp := 0
stoped := time.After(time.Second * 10)
data := que.BuildMessage([]byte("hello"))
for {
select {
case <-stoped:
fmt.Println(count, cp)
stop <- struct{}{}
return
default:
que.ParseMessage(data, "lala")
cp++
}
}
}