·设为首页收藏本站📧邮箱修改🎁免费下载专区💎积分✅卡密📒收藏夹👽聊天室
返回列表 发布新帖

Golang实用封装函数集一

350 2
发表于 2023-4-21 16:12:08 | 查看全部 阅读模式

马上注册,免费下载更多dz插件网资源。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
取上月/周开始、结束时间:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

func get_lastmonth_begin_end() (map[string]interface{} ) {
     
   now := time.Now()
   lastMonthFirstDay := now.AddDate(0, -1, -now.Day()+1)//利用此特性,可以得到上周 now.AddDate(0, 0, -int(now.Weekday())-6)的开始时间
   lastMonthStart := time.Date(lastMonthFirstDay.Year(), lastMonthFirstDay.Month(), lastMonthFirstDay.Day(), 0, 0, 0, 0, now.Location()).Unix()
   lastMonthEndDay := lastMonthFirstDay.AddDate(0, 1, -1)
   lastMonthEnd := time.Date(lastMonthEndDay.Year(), lastMonthEndDay.Month(), lastMonthEndDay.Day(), 23, 59, 59, 0, now.Location()).Unix()

     
    ret := make(map[string]interface{})
    ret["time_begin_format"] = time.Unix(lastMonthStart, 0).Format("2006-01-02 15:04:05")
    ret["time_end_format"]   = time.Unix(lastMonthEnd, 0).Format("2006-01-02 15:04:05")
     
  
    ret["time_begin"]        = lastMonthStart
    ret["time_end"]          = lastMonthEnd
     
    return ret
}
执行结果:
map[time_begin_format:2020-12-01 00:00:00 time_end_format:2020-12-31 23:59:59 time_begin:1606752000 time_end:1609430399]




取本周一,周末时间:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

func get_weekday_begin_end() (map[string]interface{} ) {
    now := time.Now()

    offset := int(time.Monday - now.Weekday())
  
    weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
    weekMonday := weekStartDate.Format("2006-01-02")

    TimeMonday, _ := time.Parse("2006-01-02", weekMonday)
    lastWeekMonday := TimeMonday.AddDate(0, 0, 6)
    enddate := time.Date(lastWeekMonday.Year(), lastWeekMonday.Month(), lastWeekMonday.Day(), 23, 59, 59, 0, time.Local)
    end := enddate.Format("2006-01-02 15:04:05")
     
     
    ret := make(map[string]interface{})
    ret["time_begin_format"] = weekMonday
    ret["time_end_format"]  = end
     
  
    ret["time_begin"]    = weekStartDate.Unix()
    ret["time_end"]     = enddate.Unix()
     
    return ret
}

执行结果:
map[time_begin_format:2021-01-18 time_end_format:2021-01-24 23:59:59 time_begin:1610899200 time_end:1611503999]

我要说一句 收起回复
创宇盾启航版免费网站防御网站加速服务

评论2

TyCodingLv.8 发表于 2023-4-21 16:12:55 | 查看全部
//分享一个比较字符串数字差值的函数:

// CalcBudgetDiff 计算预算差值
func CalcBudgetDiff(start, end string) (float64, error) {
    s1, err := strconv.ParseFloat(start, 64)
    if err != nil {
        return 0.00, err
    }
    e1, err := strconv.ParseFloat(end, 64)
    if err != nil {
        return 0.00, err
    }
    d1 := e1 - s1
    f, err := strconv.ParseFloat(fmt.Sprintf("%.2f", d1), 64)
    if err != nil {
        return 0.00, err
    }
    return f, nil
}



//Curl函数,phper最为熟悉
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

// Curl 网络请求函数
// @Summary 网络请求函数
// @Description 网络请求函数
// @Tags 网络请求函数
// @Param method: GET/POST string
// @Param dataStr string k1=v1&k2=v2或者json数据,由header头决定
// @Param header map[string]string
// @Success string, nil
func Curl(method string, urls string, dataStr string, header map[string]string) ([]byte, error) {
   client := &http.Client{}
   req, err := http.NewRequest(method, urls, strings.NewReader(dataStr))
   if err != nil {
      return nil, err
   }
   if header != nil {
      for k, v := range header {
         req.Header.Set(k, v)
      }
   }
   resp, err := client.Do(req)
   if err != nil {
      return nil, err
   }
   if resp.Body == nil {
      return nil, errors.New("resp.Body is empty")
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      return nil, err
   }
   if body == nil || len(body) == 0 {
      return nil, errors.New("httpDo返回的body为空")
   }
   return body, nil
}


//用于打印参数:
1

2

3

4

5

6

7

func Debug(param ...interface{}) {
   fmt.Println("+++++++++++++")
   for _, v := range param {
      fmt.Println(fmt.Sprintf("%+v", v))
   }
   fmt.Println("+++++++++++++")
}


//跨域处理
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

//跨域处理
func CrosHandler() gin.HandlerFunc {
    return func(context *gin.Context) {
        method := context.Request.Method
        context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
        context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
        context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
        context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
        context.Header("Access-Control-Max-Age", "172800")
        context.Header("Access-Control-Allow-Credentials", "false")
        context.Set("content-type", "application/json")  设置返回格式是json
         
        if method == "OPTIONS" {
            context.JSON(http.StatusOK, result.Result{Code: result.OK, Data: "Options Request!"})
        }

        //处理请求
        context.Next()
    }
}

我要说一句 收起回复
独家记忆Lv.8 发表于 2023-4-21 16:13:55 | 查看全部
  1. //跨域访问:cross  origin resource share
  2. func CrosHandler() gin.HandlerFunc {
  3.     return func(context *gin.Context) {
  4.         method := context.Request.Method
  5.         context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  6.         context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
  7.         context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  8.         context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
  9.         context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
  10.         context.Header("Access-Control-Max-Age", "172800")
  11.         context.Header("Access-Control-Allow-Credentials", "false")
  12.         context.Set("content-type", "application/json")  设置返回格式是json
  13.         if method == "OPTIONS" {
  14.            context.JSON(http.StatusOK, result.Result{Code: result.OK, Data: "Options Request!"})
  15.         }
  16.         //处理请求
  17.         context.Next()
  18.     }
  19. }
复制代码
我要说一句 收起回复

回复

 懒得打字嘛,点击右侧快捷回复【查看最新发布】   【应用商城享更多资源】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

创宇盾启航版免费网站防御网站加速服务
投诉/建议联系

discuzaddons@vip.qq.com

未经授权禁止转载,复制和建立镜像,
如有违反,按照公告处理!!!
  • 联系QQ客服
  • 添加微信客服

联系DZ插件网微信客服|最近更新|Archiver|手机版|小黑屋|DZ插件网! ( 鄂ICP备20010621号-1 )|网站地图 知道创宇云防御

您的IP:18.223.170.253,GMT+8, 2024-12-22 16:33 , Processed in 0.207789 second(s), 91 queries , Gzip On, Redis On.

Powered by Discuz! X5.0 Licensed

© 2001-2024 Discuz! Team.

关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表