2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
顯然,您不應(yīng)該每次出現(xiàn)請求時(shí)都創(chuàng)建處理程序。他們從不釋放內(nèi)存,所以你最終會遇到內(nèi)存不足的異常。
相反,將處理程序端點(diǎn)放入數(shù)組(切片)并使用 ONE 處理程序,該處理程序通過查看此切片中的 URL 來響應(yīng)請求,然后從切片中刪除不再需要的項(xiàng)目。
所以基本上,而不是
routeHtml := "/api/html/" + dir
http.HandleFunc(routeHtml, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//writes Template to 'w' http.ResponseWriter
fmt.Fprintf(w, buf.String())
fmt.Println("successfull Operation 2 !!")
fmt.Println("")
job_2.Complete(health.Success)
}))
做
type JobInfo struct {
Path string
// some data here
}
// maybe global context
var jobs []JobInfo
// initialisation
jobs = make([]JobInfo, 0)
http.HandleFunc("/api/html/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
var job *JobInfo
for _, j := range jobs {
if j.Path == path {
job = &j
break
}
}
if job != nil {
// handle job request here
}
}))
// and then in the jobs' loop
handlers = append(handlers, JobInfo{"/api/html/" + dir, ...})
它會起作用,因?yàn)椋?/p>
模式命名固定的根路徑,如“/favicon.ico”,或根子樹,如“/images/”(注意尾部斜杠)。較長的模式優(yōu)先于較短的模式,因此如果“/images/”和“/images/thumbnails/”都注冊了處理程序,則將為以“/images/thumbnails/”和前者開頭的路徑調(diào)用后一個(gè)處理程序?qū)⒔邮諏Α?images/”子樹中任何其他路徑的請求。
jobs當(dāng)然,不要忘記清理數(shù)組。

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
而不是使用切片最好使用地圖
type JobInfo struct {
Path string
// some data here
}
// global context
var jobs map[string]JobInfo
// initialisation
jobs = make(map[string]JobInfoStruct)
http.HandleFunc("/api/html/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
var job JobInfoStruct
var ok bool
job, ok = jobs[path]
if ok {
// handle job request here
//then after delete the job
delete(jobs, path)
}
}))
// and then in the jobs' loop
pathVideo := "/api/html/" + dir
jobs[pathVideo] = JobInfoStruct{pathVideo, ...}
- 2 回答
- 0 關(guān)注
- 286 瀏覽
添加回答
舉報(bào)