dongqing5925
2017-08-25 09:05
浏览 31
已采纳

如何使用Go http包提供共享结构?

I have a struct with many fields (some of them are pointers to other structs as well) which are being continuosly updated in a separate goroutine. The same struct is accessed from go's http template when a page is served.

Code example:

type SharedStruct struct {
     Description string
     Counter int
     Status_ *Status
     LastChecked time.Time
     //other fields
} 
var shared = &SharedStruct{}

go func() {
    //..updates fields every 5 minutes
}()

go-http handler:

func someHandler(w http.ResponseWriter, r *http.Request) {
   t.ExecuteTemplate(w, "page.html", shared)
}

and page.html template:

...
Status: {{.Status_.StatusCode}}
Counter: {{.Counter}}
Last checked: {{.LastChecked.Format "2006-02-01 15:04:05"}}

So far everything works as expected, but I'm aware that bad things can happen without any synchronization. What is the preferred way to handle this properly?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题