问题描述
我正在使用 httprouter 来解析api调用路径中的一些参数:
I'm using httprouter for parsing some parameters from the path in api calls:
router := httprouter.New()
router.GET("/api/:param1/:param2", apiHandler)
,并希望将一些文件添加到根目录(/
)进行服务.只是index.html
,script.js
和style.css
.全部位于名为static
And wanted to add some files to the root (/
) to serve. It's just index.html
, script.js
and style.css
. All in a local directory called static
router.ServeFiles("/*filepath", http.Dir("static"))
这样我就可以随浏览器一起使用localhost:8080/
,它将服务于index.html
,而来自浏览器的js
将调用/api/:param1/:param2
So that I can go with the browser to localhost:8080/
and it will serve index.html
and the js
from the browser will call the /api/:param1/:param2
但是此路径与/api
路径冲突.
But this path conflicts with the /api
path.
panic: wildcard route '*filepath' conflicts with existing children in path '/*filepath'
推荐答案
正如其他人指出的那样,仅使用github.com/julienschmidt/httprouter
是不可能的.
As others pointed out, this is not possible using only github.com/julienschmidt/httprouter
.
请注意,这可以使用标准库的多路复用器来实现,如以下答案中所述:如何通过使用相同的端口地址和不同的句柄模式来服务网页和API路由
Note that this is possible using the multiplexer of the standard library, as detailed in this answer: How do I serve both web pages and API Routes by using same port address and different Handle pattern
如果必须从根本上提供所有Web内容,则另一个可行的解决方案是将标准路由器和julienschmidt/httprouter
混合使用.使用标准路由器在根目录处注册和提供文件,并使用julienschmidt/httprouter
满足您的API请求.
If you must serve all your web content at the root, another viable solution could be to mix the standard router and julienschmidt/httprouter
. Use the standard router to register and serve your files at the root, and use julienschmidt/httprouter
to serve your API requests.
它是这样的:
router := httprouter.New()
router.GET("/api/:param1/:param2", apiHandler)
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("static")))
mux.Handle("/api/", router)
log.Fatal(http.ListenAndServe(":8080", mux))
在上面的示例中,所有以/api/
开头的请求都将转发到router
处理程序,其余的将由文件服务器尝试处理.
In the example above, all requests that start with /api/
will be forwarded to the router
handler, and the rest will be attempted to handle by the file server.
这篇关于在root上提供静态内容,在/api上提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!