登录
首页 >  Golang >  Go问答

设置日期和日期数组的文件和结构

来源:stackoverflow

时间:2024-02-28 17:51:26 497浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《设置日期和日期数组的文件和结构》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我必须在 60 秒后为每个请求保存一条记录,我必须将其保存到我的 appsettings.json 中,例如记录

09/13/2019 11:38 am: request count last 60s : 4
09/13/2019 12:40 pm: request count last 60s : 6

在我的结构中,我将其设置为

// appsettings struct
    appsettings struct {
        requests []requests `request`
    }

    // requests struct
    requests struct {
        requestdate string      `requestdate`
        datas       []time.time `datas`
    }

我的目标是统计60s后的请求数,统计请求数。

如果您有任何建议,我该如何显示此内容

09/13/2019 11:38 am: request count last 60s : 4
09/13/2019 12:40 pm: request count last 60s : 6

并将其存储在我的文件中。


解决方案


此示例代码:

package main

import (
    "fmt"
    "time"
)

type requests struct {
    requestdate string      `requestdate`
    datas       []time.time `datas`
}

type appsettings struct {
    requests []requests `request`
}

var appsettings appsettings

func addrequest(requesttime time.time) {
    timestring := requesttime.format("01/02/2006 03:04 pm")

    requestfound := false
    for key, request := range appsettings.requests {
        if request.requestdate == timestring {
            requestfound = true
            request.datas = append(request.datas, requesttime)
            appsettings.requests[key] = request
        }
    }

    if requestfound == false {
        newrequest := requests{
            requestdate: timestring,
            datas: make([]time.time, 0),
        }
        newrequest.datas = append(newrequest.datas, requesttime)
        appsettings.requests = append(appsettings.requests, newrequest)
    }
}

func printrequests() {
    for _, request := range appsettings.requests {
        fmt.printf("%s: request count last 60s : %d\n", request.requestdate, len(request.datas))
    }
}

func main() {
    appsettings = appsettings{}
    appsettings.requests = make([]requests, 0)

    requesttime, _ := time.parse(time.rfc3339, "2006-09-13t11:04:00z")
    addrequest(requesttime)

    requesttime, _ = time.parse(time.rfc3339, "2006-09-13t15:04:00z")
    addrequest(requesttime)

    requesttime, _ = time.parse(time.rfc3339, "2006-09-13t15:04:59z")
    addrequest(requesttime)

    requesttime, _ = time.parse(time.rfc3339, "2006-09-13t15:05:01z")
    addrequest(requesttime)

    printrequests()
}

重现此输出:

09/13/2006 11:04 AM: request count last 60s : 1
09/13/2006 03:04 PM: request count last 60s : 2
09/13/2006 03:05 PM: request count last 60s : 1

前往演示链接:https://play.golang.org/p/XqyhScHDW8R

今天关于《设置日期和日期数组的文件和结构》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>