1 回答

TA貢獻2019條經驗 獲得超9個贊
在您的情況下,只需要構建處理程序。它必須指向目錄而不是文件。除了路由之外,其余處理程序均已過時。
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"time"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/route1", index).Methods("GET")
r.HandleFunc("/route2", index).Methods("GET")
buildHandler := http.FileServer(http.Dir("client/build"))
r.PathPrefix("/").Handler(buildHandler)
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8080",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
fmt.Println("Server started on PORT 8080")
log.Fatal(srv.ListenAndServe())
}
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "client/build/index.html")
}
僅使用標準庫即可實現相同的效果。
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
r := http.NewServeMux()
r.HandleFunc("/route1", index)
r.HandleFunc("/route2", index)
buildHandler := http.FileServer(http.Dir("client/build"))
r.Handle("/", buildHandler)
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8080",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
fmt.Println("Server started on PORT 8080")
log.Fatal(srv.ListenAndServe())
}
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "client/build/index.html")
}
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報