123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package conv
- import (
- "crypto/tls"
- "encoding/json"
- "errors"
- "gadmin/utility"
- "github.com/nahid/gohttp"
- "github.com/sirupsen/logrus"
- "io"
- "net"
- "net/http"
- "os"
- "strconv"
- "strings"
- "time"
- )
- func GetUrlBody(version string, fileName string) ([]byte, error) {
- url := utility.PullJsonAddr(version, fileName)
- logrus.Info("GetUrlBody url:", url)
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- DisableCompression: true,
- Dial: func(netw, addr string) (net.Conn, error) {
- deadline := time.Now().Add(15 * time.Second)
- c, err := net.DialTimeout(netw, addr, time.Second*3)
- if err != nil {
- return nil, err
- }
- c.SetDeadline(deadline)
- return c, nil
- },
- }
- a1 := gohttp.SetTransport(tr)
- req := gohttp.NewRequest(a1)
- resp, err := req.Get(url)
- if err != nil {
- return nil, err
- }
- if resp.GetStatusCode() != 200 {
- return nil, errors.New(strconv.Itoa(resp.GetStatusCode()))
- }
- return resp.GetBodyAsByte()
- }
- func SaveJsonPath(filePath string, v interface{}) {
- logrus.Infoln("Create filePath:", filePath)
- index := strings.LastIndex(filePath, "/")
- if index == -1 {
- logrus.Errorln("文件路径错误!")
- return
- }
- utility.CreateDir(filePath[:index])
- ptrFile2, err := os.Create(filePath)
- if err != nil {
- logrus.Errorln("写日志文件失败", err)
- }
- defer ptrFile2.Close()
- encoder := json.NewEncoder(ptrFile2)
- if err = encoder.Encode(&v); err != nil {
- logrus.Infoln("Encoder failed", err.Error())
- } else {
- logrus.Infoln("Encoder success")
- }
- }
- func HttpRequestToFile(url string, dstFileName string) error {
- logrus.Infof("HttpRequestToFile url:%v ,dstFileName:%v", url, dstFileName)
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- DisableCompression: true,
- Dial: func(netw, addr string) (net.Conn, error) {
- deadline := time.Now().Add(15 * time.Second)
- c, err := net.DialTimeout(netw, addr, time.Second*3)
- if err != nil {
- return nil, err
- }
- c.SetDeadline(deadline)
- return c, nil
- },
- }
- a1 := gohttp.SetTransport(tr)
- req := gohttp.NewRequest(a1)
- resp, err := req.Get(url)
- if err != nil {
- return err
- }
- if resp.GetStatusCode() != 200 {
- return errors.New(strconv.Itoa(resp.GetStatusCode()))
- }
- body := resp.GetBody()
- if body == nil {
- return nil
- }
- defer body.Close()
- dstFile, err := os.Create(dstFileName) //, os.O_WRONLY|os.O_CREATE, 0755)
- if err != nil {
- return err
- }
- io.Copy(dstFile, body)
- return nil
- }
|