You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
starnet/curl.go

126 lines
2.6 KiB
Go

package starnet
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"
)
type Request struct {
TimeOut int
DialTimeOut int
Url string
Method string
RecvData []byte
WriteRecvData bool
RecvIo io.Writer
ReqHeader http.Header
ReqCookies []*http.Cookie
RespHeader http.Header
RespCookies []*http.Cookie
RespHttpCode int
PostBuffer *bytes.Buffer
CircleBuffer *CircleByteBuffer
Proxy string
}
func NewRequests(url string, postdata []byte, method string) Request {
return Request{
TimeOut: 30,
DialTimeOut: 15,
Url: url,
PostBuffer: bytes.NewBuffer(postdata),
Method: method,
}
}
func (curl *Request) ResetReqHeader() {
curl.ReqHeader = make(http.Header)
}
func (curl *Request) ResetReqCookies() {
curl.ReqCookies = []*http.Cookie{}
}
func (curl *Request) AddSimpleCookie(key, value string) {
curl.ReqCookies = append(curl.ReqCookies, &http.Cookie{Name: key, Value: value, Path: "/"})
}
func randomBoundary() string {
var buf [30]byte
_, err := io.ReadFull(rand.Reader, buf[:])
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", buf[:])
}
func Curl(curl Request) (resps Request, err error) {
var req *http.Request
if curl.Method == "" {
return Request{}, errors.New("Error Method Not Entered")
}
if curl.PostBuffer != nil {
req, err = http.NewRequest(curl.Method, curl.Url, curl.PostBuffer)
} else {
req, err = http.NewRequest(curl.Method, curl.Url, curl.CircleBuffer)
}
if err != nil {
return
}
req.Header = curl.ReqHeader
if len(curl.ReqCookies) != 0 {
for _, v := range curl.ReqCookies {
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, _ := url.Parse(curl.Proxy)
transport.Proxy = http.ProxyURL(purl)
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
curl.PostBuffer = nil
curl.CircleBuffer = nil
curl.RespHttpCode = resp.StatusCode
curl.RespHeader = resp.Header
curl.RespCookies = resp.Cookies()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if curl.WriteRecvData {
curl.RecvData = body
}
if curl.RecvIo != nil {
_, err = curl.RecvIo.Write(body)
}
return curl, err
}