找回密码
 立即注册
搜索
查看: 677|回复: 2

[go基础] Golang实用封装函数集一

  [复制链接]
发表于 2023-2-9 17:10 | 显示全部楼层 |阅读模式

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

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]


匿名
匿名  发表于 2023-2-9 17:26
//分享一个比较字符串数字差值的函数:
 
// 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()
    }
}


 楼主| 发表于 2023-2-28 21:33 | 显示全部楼层
//跨域访问:cross  origin resource share
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()
    }
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|学习笔记

GMT+8, 2024-12-21 20:15 , Processed in 0.037324 second(s), 14 queries , APCu On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表