封面
This commit is contained in:
35
main.go
35
main.go
@@ -21,7 +21,23 @@ func main() {
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
|
||||
r := mux.NewRouter()
|
||||
r.Use(middleware)
|
||||
|
||||
// 設定中間件
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer LogComponent(time.Now().UnixNano(), r) // 最后打印日志
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*") // 處理跨域請求
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
if r.Method == "OPTIONS" {
|
||||
w.WriteHeader(http.StatusOK) // 處理OPTIONS請求
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
})
|
||||
|
||||
// 設定路由
|
||||
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.ParseFiles("templates/index.html")
|
||||
t.Execute(w, nil)
|
||||
@@ -308,23 +324,6 @@ func tasks_item_delete(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(ToJSON(task))
|
||||
}
|
||||
|
||||
// 中間件, 通用
|
||||
func middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer LogComponent(time.Now().UnixNano(), r) // 最后打印日志
|
||||
// 處理跨域請求
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
// 處理OPTIONS請求
|
||||
if r.Method == "OPTIONS" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func ToJSON(object interface{}) []byte {
|
||||
json, err := json.MarshalIndent(object, "", " ")
|
||||
if err != nil {
|
||||
|
Reference in New Issue
Block a user