如何在 Go 中每秒重复 N 次函数?
我可以:
N := 30 //Repeat 30 times per second
for {
//Do something
time.Sleep(time.Second * time.Duration(N))
}
Run Code Online (Sandbox Code Playgroud)
但这只是使重复之间的间隔
模板“head”插入“index”模板并使用一个变量 {{ .Title }}
主要.go:
package main
import (
"html/template"
"net/http"
"github.com/julienschmidt/httprouter"
)
var (
t = template.Must(template.ParseGlob("templates/*.tpl"))
)
type Page struct {
Title string
Desc string
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
index := Page{Title: "This is title", Desc: "Desc"}
t.ExecuteTemplate(w, "index", index)
}
func main() {
router := httprouter.New()
router.GET("/", Index)
http.ListenAndServe(":8080", router)
}
Run Code Online (Sandbox Code Playgroud)
索引.tpl:
{{ define "index" }}
<!DOCTYPE html>
<html lang="en">
{{ template "head" }}
<body>
<h1>Main info:</h1>
Title: {{ .Title }}
Desc: …Run Code Online (Sandbox Code Playgroud) 我从基部获取正常的字节切片(由 json.Marshal 制作的切片)并尝试解码它们,但是 json.unmarshal() - 返回 nil
代码 :
coded := redis.LoadFromBase()
uncoded := json.Unmarshal(coded, &p)
fmt.Println("Bytes:", coded)
fmt.Println("Unmarshalled:", uncoded)
Run Code Online (Sandbox Code Playgroud)
回到:
Bytes: [123 34 84 105 116 108 101 34 58 34 97 34 44 34 67 111 110 116 101 110 116 34 58 34 98 34 125]
Unmarshalled: <nil>
Run Code Online (Sandbox Code Playgroud)
LoadFromBase() 工作正常