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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案