登录
首页 >  Golang >  Go问答

golang 服务器中的刷新或直接请求URL路径时返回 404 响应

来源:stackoverflow

时间:2024-02-06 10:27:22 338浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《golang 服务器中的刷新或直接请求URL路径时返回 404 响应》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有这个代码来服务反应构建应用程序:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {

    r := http.NewServeMux()

    r.HandleFunc(`^/`, index)
    buildHandler := http.FileServer(http.Dir("build"))
    r.Handle("/", buildHandler)

    srv := &http.Server{
        Handler:      r,
        Addr:         ":5000",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    fmt.Println("Server started on PORT 5000")
    log.Fatal(srv.ListenAndServe())

}

func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "build/index.html")
}

文件夹结构如下所示:

但是我在刷新或尝试直接转到路径时收到 404 not found。如何让它转到所需的路径而不是 404?


正确答案


您遇到的问题与 react(或其他前端框架)使用的客户端路由有关。当您刷新页面或直接访问特定路径时,服务器无法识别该路由,因为它主要提供静态 index.html 文件,而不处理客户端路由。

要解决此问题,您需要将 go 服务器配置为通过将所有请求重定向到 index.html 文件来处理客户端路由。这样,react 应用程序中的客户端路由就可以接管并处理正确的页面显示。

以下是处理客户端路由的修改后的代码:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {
    r := http.NewServeMux()

    // Redirect all requests to the index.html file
    r.HandleFunc("/", index)

    // Serve the static files from the "build" directory
    buildHandler := http.FileServer(http.Dir("build"))
    r.Handle("/static/", buildHandler)
    r.Handle("/js/", buildHandler)
    r.Handle("/css/", buildHandler)

    srv := &http.Server{
        Handler:      r,
        Addr:         ":5000",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    fmt.Println("Server started on PORT 5000")
    log.Fatal(srv.ListenAndServe())
}

func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "build/index.html")
}

在修改后的代码中,我们通过将根路径(“/”)的请求重定向到index.html 文件来处理它们。此外,我们使用 http.fileserver 从“build”目录提供静态文件(js、css 等)。通过这样做,您的服务器将正确地为所有路由提供 index.html 文件,并且 react 应用程序中的客户端路由将负责显示适当的页面。

终于介绍完啦!小伙伴们,这篇关于《golang 服务器中的刷新或直接请求URL路径时返回 404 响应》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>