简体   繁体   English

在root上提供静态内容,在/ api上提供静态内容

[英]Serve static content on root and rest on /api

I'm using httprouter for parsing some parameters from the path in api calls: 我正在使用httprouter从api调用中的路径中解析一些参数:

router := httprouter.New()
router.GET("/api/:param1/:param2", apiHandler)

And wanted to add some files to the root ( / ) to serve. 并希望将一些文件添加到根目录( / )进行服务。 It's just index.html , script.js and style.css . 就是index.htmlscript.jsstyle.css All in a local directory called static 全部位于称为static的本地目录中

router.ServeFiles("/*filepath", http.Dir("static"))

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 这样我就可以使用浏览器进入localhost:8080/ ,它将提供index.html并且来自浏览器的js会调用/api/:param1/:param2

But this path conflicts with the /api path. 但是此路径与/api路径冲突。

panic: wildcard route '*filepath' conflicts with existing children in path '/*filepath'

As others pointed out, this is not possible using only github.com/julienschmidt/httprouter . 正如其他人指出的那样,仅使用github.com/julienschmidt/httprouter是不可能的。

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 请注意,这可以使用标准库的多路复用器来实现,如以下答案所述: 我如何通过使用相同的端口地址和不同的句柄模式来服务网页和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 . 如果您必须从根本上提供所有Web内容,那么另一个可行的解决方案是将标准路由器和julienschmidt/httprouter Use the standard router to register and serve your files at the root, and use julienschmidt/httprouter to serve your API requests. 使用标准路由器在根目录处注册和提供文件,并使用julienschmidt/httprouter服务您的API请求。

This is how it could look like: 它看起来像这样:

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))

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. 在上面的示例中,所有以/api/开头的请求都将转发到router处理程序,其余的将由文件服务器尝试处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM