我必须在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`
}
我的目标是计算60秒后的请求数量并计算请求。
如果您有任何建议,我该如何显示
09/13/2019 11:38 AM: request count last 60s : 4
09/13/2019 12:40 PM: request count last 60s : 6
并将其存储在我的文件中。
答案 0 :(得分:2)
此示例代码:
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