dp518158 2015-02-18 02:17
浏览 30
已采纳

去大猩猩多路复用器不按预期路线

I am having issues getting the Gorilla Mux library for Go to work. From the documentation I have read and all the debugging I've done, I cannot seem to figure out what the problem is. Here's what I've got for routing:

Folder structure:

project_root
  |-- main.go
  |-- routes
         |-- routes.go
         |-- user.go

main.go:

package main

import (
    "fmt"
    "net/http"

    "./routes"
)

func main() {
    r := routes.CreateRoutes(http.Dir("./content"))

    http.Handle("/", r)
    err := http.ListenAndServe(fmt.Sprintf("%s:%d", "localhost", 8000), nil)
    if err != nil {
        fmt.Println("Error: ", err)
    }
}

routes/routes.go

package routes

import (
    "net/http"

    "github.com/gorilla/mux"
)

func CreateRoutes(staticDir http.FileSystem) *mux.Router {
    r := mux.NewRouter()

    // Serve static pages (i.e. web app)
    r.PathPrefix("/").Handler(http.FileServer(staticDir))

    // Serve User Pages
    createUserRoutes(r)

    return r
}

routes/user.go

package routes

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func createUserRoutes(r *mux.Router) {
    user := r.PathPrefix("/user/").Subrouter()

    // Create a new user
    user.Path("/new").Methods("PUT").HandlerFunc(newUserHandler)

    // Remove a user
    user.Path("/remove/{username:[a-z][a-z0-9]+}").Methods("DELETE").HandlerFunc(removeUserHandler)

    // Update a user
    user.Path("update/{username:[a-z][a-z0-9]+").Methods("POST").HandlerFunc(updateUserHandler)

    // Get a user (Get user information)
    user.Path("/{username:[a-z][a-z0-9]+").Methods("GET").HandlerFunc(getUserHandler)
}

func newUserHandler(resp http.ResponseWriter, req *http.Request) {
    // Do something that might cause an error        

    if err != nil {
        fmt.Println(err)
        resp.WriteHeader(409)
        resp.Write([]byte(err.Error()))
    } else {
        fmt.Println("Created new user")
        resp.WriteHeader(201)
        resp.Write([]byte("Created new user"))
    }
}

func removeUserHandler(resp http.ResponseWriter, req *http.Request) {
}

func updateUserHandler(resp http.ResponseWriter, req *http.Request) {
}

func getUserHandler(resp http.ResponseWriter, req *http.Request) {
}

Whenever I make a request to root path of the server (i.e. the path that serves the static content), the server responds as intended, with the main page. However, any other calls result in a 404 response (I test requests using cURL). For example, a malformed request to http://localhost:8000/user/new should return a 409, but instead returns a 404. Same if I expect a 201 response.

Everything looks right and I've triple checked it, but I cannot figure out what the issue here is.

  • 写回答

1条回答 默认 最新

  • douche3244 2015-02-19 02:44
    关注

    Turns out the solution was simple (like it usually is). This line in routes.go

    r.PathPrefix("/").Handler(http.FileServer(staticDir))
    

    was causing the unintended routing. When PathPrefix is used, it seems to route all URLs to the first matching prefix (in this case this prefix). This explains why static files were being served, but nothing else works.

    The fix is to use the Path function instead. There's a subtle difference as explained in the docs; PathPrefix "matches if the given template is a prefix of the full URL path", whereas Path does not. Hence the line above now looks like this to solve the issue I was having:

    r.Path("/").Handler(http.FileServer(staticDir))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度