告诉我,是否可以创建一个自动插入标准标头的函数,例如,如果我在 /api 处处理
http.HandleFunc("/api/count_users", countUsersHandler)
http.HandleFunc("/api/count_payments", countPaymentsHandler)
http.HandleFunc("/api/average_payments", averagePaymentHandler)
那么在所有情况下,您都需要在每个函数中编写标题:
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
并且在所有情况下您都需要转换为 json:
json.NewEncoder(w).Encode(response)
是否可以创建一个函数(例如 API),并简单地将所有这些自动添加到对 API 的每个请求中?像这样:
func countPaymentsHandler(w http.ResponseWriter, r *http.Request) {
var count int
err := db.QueryRow("SELECT COUNT(*) FROM payments WHERE `status` = '1'").Scan(&count)
if err != nil {
http.Error(w, "Ошибка при выполнении запроса", http.StatusInternalServerError)
return
}
response := map[string]int{"count": count}
return response
}
func API(pattern string, handler func()) {
http.HandleFunc("/api/"+pattern, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
response := handler
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
}
func main() {
initDB()
defer db.Close()
API("count_payments", countPaymentsHandler)
fmt.Println("Сервер запущен на http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}