You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gorilla/Mux的Go API中/login与/register路由返回404问题

问题分析与修复方案

错误原因

你遇到的404问题,核心是错误使用了path.Dir()函数:

  • path.Dir(filePath)的作用是提取文件路径中的目录部分,而非返回文件本身。比如path.Dir("./public/views/login.html")返回的是./public/views,而非login.html文件。
  • 首页能正常显示是偶然情况:当http.ServeFile接收到目录路径时,会自动尝试加载目录下的index.html作为默认页面,所以首页的错误代码刚好歪打正着生效了。但/login和/register路由中,http.ServeFile加载的是./public/views目录,不会自动去查找login.html或register.html,因此返回404。

修复步骤

直接移除path.Dir()包裹,使用文件的完整路径即可,推荐用path.Join()做跨平台路径兼容:

修改后的代码

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "go-api/controller/ad"
    "log"
    "net/http"
    "path"
)

func homePage(w http.ResponseWriter, r *http.Request) {
    p := path.Join("public", "views", "index.html")
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

func showLogin(w http.ResponseWriter, r *http.Request) {
    p := path.Join("public", "views", "login.html")
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

func showRegister(w http.ResponseWriter, r *http.Request) {
    p := path.Join("public", "views", "register.html")
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

func main() {
    baseUrl := "localhost:9010"

    r := mux.NewRouter()
    r.HandleFunc("/", homePage).Methods("GET")

    r.HandleFunc("/ads", ad.GetAds).Methods("GET")

    r.HandleFunc("/login", showLogin).Methods("GET")
    r.HandleFunc("/register", showRegister).Methods("GET")

    http.Handle("/", r)
    fmt.Printf("Server running at: http://%s\n", baseUrl)
    log.Fatal(http.ListenAndServe(baseUrl, nil))
}

额外说明

  • path.Join()会自动适配不同操作系统的路径分隔符,让代码更具跨平台兼容性。
  • 原代码中r.HandleFunc("/ads", Ad.GetAds)的Ad应为小写ad,与导入的包名对应,已帮你修正该潜在编译错误。

内容的提问来源于stack exchange,提问作者mheonyae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:21:00