函數(shù)式編程
2023-07-31 16:36:40
我意識到在構(gòu)建 Web 服務(wù)器時,處理它們的所有路由和函數(shù)都在文件中main.go。隨著應(yīng)用程序的增長,我想可能很難跟蹤所有內(nèi)容。是否有關(guān)于將路由和處理程序函數(shù)“存儲”在除 之外的文件中的約定main.go?
1 回答

HUX布斯
TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊
我是這樣做的。假設(shè)您有一個檢查數(shù)據(jù)庫連接的 ping 處理程序,并且將其放在名為 的包中your/app/animal:
package animal
...
func Ping(db *sql.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := db.PingContext(context.TODO()); err != nil {
http.Error(w, err, http.StatusInternalServerError)
}
})
}
你可以這樣設(shè)置:
package main
...
func main() {
db, _ := sql.Open("foo",os.GetEnv("DB"))
http.Handle("/ping",animal.Ping(db))
log.Fatal(http.ListenAndServe(os.GetEnv("BIND"),nil)
}
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報
0/150
提交
取消