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 关注
- 110 浏览
添加回答
举报