This commit is contained in:
fallen-angle
2022-01-20 16:49:37 +08:00
parent 2280679053
commit 582807ae10
13 changed files with 182 additions and 16 deletions

View File

@@ -1,8 +1,10 @@
package global
import (
"errors"
"fmt"
"nCovTrack-Backend/config"
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -14,8 +16,21 @@ var (
Db *gorm.DB
RootRouter *gin.RouterGroup
Logger *zap.SugaredLogger
HttpClient map[string]*http.Client
)
func GetListenOn() string {
return fmt.Sprintf("%s:%d", ServerSettings.Listen, ServerSettings.Port)
}
func GetHttpClient(key string) (*http.Client, error) {
client := HttpClient[string(key)]
if client == nil {
return nil, errors.New("Not fount the http client: " + key)
}
return client, nil
}
const (
CHINA_NCOV_STATISTIC_URL = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5"
)

19
initialize/http_client.go Normal file
View File

@@ -0,0 +1,19 @@
package initialize
import (
"nCovTrack-Backend/global"
"net/http"
"time"
)
func initHttpClient() {
clientMap := make(map[string]*http.Client)
clientMap[""] = defaultClient()
global.HttpClient = clientMap
}
func defaultClient() *http.Client {
return &http.Client{
Timeout: time.Duration(5 * time.Second),
}
}

View File

@@ -5,6 +5,7 @@ import "github.com/gin-gonic/gin"
func Initialize() *gin.Engine {
initConfig()
initLogger()
initHttpClient()
initMySQL()
return initRouter()
}

View File

@@ -10,7 +10,8 @@ import (
func initRouter() *gin.Engine {
r := gin.New()
r.Use(middleware.Cors(), middleware.RequestLog(), middleware.GinRecovery(false))
r.Use(middleware.Cors(), middleware.RequestLog(), middleware.GinRecovery(true))
//r.Use(middleware.Cors(), middleware.RequestLog(), gin.Recovery())
global.RootRouter = r.Group(global.ServerSettings.UrlPrefix)
router.BusiRouter()
return r

View File

@@ -1,6 +1,7 @@
package middleware
import (
"fmt"
"nCovTrack-Backend/utils"
"net"
"net/http"
@@ -33,7 +34,7 @@ func GinRecovery(stack bool) gin.HandlerFunc {
"error", interface{}(err),
)
if brokenPipe {
utils.RequestLogPanic(logParams...)
utils.RequestLogError(logParams...)
c.Error(err.(error))
c.Abort()
return
@@ -46,8 +47,9 @@ func GinRecovery(stack bool) gin.HandlerFunc {
"stack", string(debug.Stack()),
)
}
utils.RequestLogPanic(logParams...)
utils.RequestLogError(logParams...)
c.AbortWithStatus(http.StatusInternalServerError)
fmt.Printf("\n%s\n", debug.Stack())
}
}()
c.Next()

View File

@@ -31,7 +31,7 @@ func RequestLog() gin.HandlerFunc {
}
// Log while request cost an unexpected time;
if cost >= 800 {
if cost.Milliseconds() >= 800 {
logParams = append(logParams,
"status", c.Writer.Status(),
"query", c.Request.URL.Query(),

8
models/utils.go Normal file
View File

@@ -0,0 +1,8 @@
package models
type UtilRequestInfo struct {
Url string
Header string
Body string
Timeout int
}

View File

@@ -2,6 +2,7 @@ package router
import (
"nCovTrack-Backend/global"
"nCovTrack-Backend/service/statistics"
"net/http"
"time"
@@ -12,12 +13,11 @@ func BusiRouter() {
userRouter := global.RootRouter.Group("/user")
{
userRouter.GET("/count", func(c *gin.Context) {
panic("count err")
time.Sleep(800 * time.Millisecond)
c.String(http.StatusOK, "OK")
})
userRouter.GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
c.JSON(http.StatusOK, statistics.GetChinaNCovStatistic())
})
}
}

View File

@@ -0,0 +1,42 @@
package statistics
import (
"encoding/json"
"fmt"
"nCovTrack-Backend/global"
"nCovTrack-Backend/utils"
"net/http"
"github.com/gin-gonic/gin"
)
func GetChinaNCovStatistics() func(c *gin.Context) {
return func(c *gin.Context) {
resp := utils.GetWhioutHeader(global.CHINA_NCOV_STATISTIC_URL)
var nCovRes map[string]string
json.Unmarshal([]byte(resp), &nCovRes)
fmt.Println(nCovRes)
var nCovResData interface{}
json.Unmarshal([]byte(nCovRes["data"]), &nCovResData)
c.JSON(http.StatusOK, nCovResData)
}
}
func GetChinaNCovStatistic() func(c *gin.Context) {
return func(c *gin.Context) {
//resp := utils.GetWhioutHeader(global.CHINA_NCOV_STATISTIC_URL)
var nCovRes map[string]string
//err := json.Unmarshal([]byte(resp), &nCovRes)
//fmt.Println(nCovRes)
//if err != nil {
// panic(err)
//}
//var nCovResData interface{}
//err := json.Unmarshal([]byte(nCovRes["data"]), &nCovResData)
//if err != nil {
// panic(err)
//}
nCovRes["1"] = "1"
c.JSON(http.StatusOK, nCovRes)
}
}

9
test/http.go Normal file
View File

@@ -0,0 +1,9 @@
package test
import (
"nCovTrack-Backend/utils"
)
func GetnCovInfo() string {
return utils.GetWhioutHeader("https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5")
}

54
utils/http.go Normal file
View File

@@ -0,0 +1,54 @@
package utils
import (
"io/ioutil"
"nCovTrack-Backend/global"
"net/http"
"time"
)
var ()
func GetWhioutHeader(url string) string {
return GetWithHeader(url, nil)
}
func GetWithHeader(url string, header map[string]string) string {
client, err := global.GetHttpClient("")
if err != nil {
var logParams []interface{}
logParams = append(logParams, "err", err)
InitLogError("httpClient", logParams)
panic(err)
}
req, _ := http.NewRequest(http.MethodGet, url, nil)
for k, v := range header {
req.Header.Add(k, v)
}
startTime := time.Now()
res, err := client.Do(req)
cost := time.Since(startTime)
var logParams []interface{}
logParams = append(logParams,
"reqest", req,
"cost", cost.String(),
)
if err != nil {
logParams = append(logParams, "errors", err)
UtilLogError("requestUtil", logParams...)
panic(err)
}
if cost.Seconds() > 1 {
logParams = append(logParams, "response", res)
UtilLogWarn("requestUtil", logParams...)
}
UtilLogInfo("requestUtil", logParams...)
bodyBytes, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
return string(bodyBytes)
}

View File

@@ -14,13 +14,9 @@ func RequestLogWarn(args ...interface{}) {
logWarn("request", args...)
}
func RequestLogPanic(args ...interface{}) {
logPanic("request", args...)
}
func InitLogPanic(component string, args ...interface{}) {
func InitLogError(component string, args ...interface{}) {
args = append(args, "component", component)
logPanic("initialize", args...)
logError("initialize", args...)
}
func InitLogInfo(component string, args ...interface{}) {
@@ -28,6 +24,21 @@ func InitLogInfo(component string, args ...interface{}) {
logInfo("initialize", args...)
}
func UtilLogInfo(utilName string, args ...interface{}) {
args = append(args, "util", utilName)
logInfo("util", args...)
}
func UtilLogError(utilName string, args ...interface{}) {
args = append(args, "util", utilName)
logError("util", args...)
}
func UtilLogWarn(utilName string, args ...interface{}) {
args = append(args, "util", utilName)
logWarn("util", args...)
}
func logInfo(msg string, args ...interface{}) {
global.Logger.Infow(msg, args...)
}
@@ -39,7 +50,3 @@ func logError(msg string, args ...interface{}) {
func logWarn(msg string, args ...interface{}) {
global.Logger.Warnw(msg, args...)
}
func logPanic(msg string, args ...interface{}) {
global.Logger.Panicw("", args...)
}

8
utils/map.go Normal file
View File

@@ -0,0 +1,8 @@
package utils
import "encoding/json"
func MapToJson(param map[string]interface{}) string {
jsonStr, _ := json.Marshal(param)
return string(jsonStr)
}