1,http封装get,postJson类
package httpUtilimport ("bytes"logxx "go-gift-panel/src/log""io""io/ioutil""net/http"
)func PostJson(url string, jsonData []byte) string {logxx.Log.Info("请求的url=", url, " 请求的JSON Data:", string(jsonData)) // 输出 JSON 格式的数据resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData)) // 发起 POST 请求if err != nil {logxx.Log.Error("ERROR postJson请求异常 http.Post err:", err)return "e"}defer func(Body io.ReadCloser) {err := Body.Close()if err != nil {logxx.Log.Error("ERROR postJson请求异常 Body.Close err:", err)}}(resp.Body)body, err := ioutil.ReadAll(resp.Body) // 读取响应内容if err != nil {logxx.Log.Error("ERROR postJson读取body异常 ioutil.ReadAll err:", err)return "e"}logxx.Log.Info("请求返回内容 Response Body:", string(body), " Response Status:", resp.Status) // 输出响应内容return string(body)
}func Get(url string) {logxx.Log.Info("请求的url=", url) // 输出resp, err := http.Get(url) // 发起 GET 请求if err != nil {logxx.Log.Error("ERROR Get请求异常 http.Post err:", err)return}defer func(Body io.ReadCloser) {err := Body.Close()if err != nil {logxx.Log.Error("ERROR Get请求异常 Body.Close err:", err)}}(resp.Body)body, err := ioutil.ReadAll(resp.Body) // 读取响应内容if err != nil {logxx.Log.Error("ERROR Get读取body异常:", err)return}logxx.Log.Info("请求返回内容 Response Body:", string(body), " Response Status:", resp.Status) // 输出响应内容
}
2,日志logxx类
package logxximport ("github.com/sirupsen/logrus""gopkg.in/natefinch/lumberjack.v2""io""os"
)var Log = logrus.New()// var file *os.Filefunc Init() {logFile := &lumberjack.Logger{Filename: "/data/giftpanel/logs/giftpanel_.log",MaxSize: 100, // megabytes 单个文件大小100MBMaxBackups: 100, //保留100个文件MaxAge: 60, //days 保留60天Compress: false, // 是否压缩 便于查询不压缩LocalTime: true, //true使用本地时区}// 设置日志级别Log.SetLevel(logrus.InfoLevel)// 设置输出文件名和代码行号Log.SetReportCaller(true)// 设置日志格式为JSON格式Log.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05.000", // 设置时间格式,包括毫秒})Log.SetOutput(logFile)// 设置同时输出到控制台和文件Log.SetOutput(io.MultiWriter(os.Stdout, logFile))
}