Serving static css and java script while using parameters in Golang using github.com/julienschmidt/httprouter

huangapple go评论70阅读模式
英文:

Serving static css and java script while using parameters in Golang using github.com/julienschmidt/httprouter

问题

所以我正在尝试为HTML模板提供静态CSS和JavaScript,但参数阻碍了我这样做的能力。

这是我的代码:

package main

import (
	"net/http"
	"html/template"
	"github.com/julienschmidt/httprouter"
	"fmt"
)

type PageData struct {
	Chapter int
	Page int
	Source string
}

func main(){

	//我使用julienschmidt路由器,因为它有我可以使用的参数
	//创建一个路由器
	router := httprouter.New()

	//创建带有参数的路由
	router.GET("/:chapter/:page",paramHandler)
	//最后创建默认路由
	router.GET("/",defaultHandler)

	//让所有静态文件正常工作
	router.ServeFiles("/:chapter/:page/*filepath",http.Dir("/js/"))

	//http.Handle("/js/",http.StripPrefix("/js/",http.FileServer(http.Dir("./public/js/"))))
	//http.Handle("/viewjs/",http.StripPrefix("/viewjs/",http.FileServer(http.Dir("./public/viewjs/"))))

	//创建一条消息告诉用户服务器运行在哪个端口
	fmt.Println("Now serving on port 8080")
	//在指定的端口上启动服务器
	http.ListenAndServe(":8080",router)
}

func defaultHandler(rw http.ResponseWriter,r *http.Request,p httprouter.Params){
	//解析HTML文件
	index := template.Must(template.ParseFiles("public/index.html"))
	chapter := 1
	page := 1
	//从服务器获取数据
	//TODO

	//测试数据
	//defaultPage := PageData{Chapter:chapter,Page:page,Source:"http://lokeshdhakar.com/projects/lightbox2/images/image-4.jpg"}

	//将HTML文件发送到浏览器
	fmt.Printf("\nThe chapter is %d and the page is %d",chapter,page)
	index.Execute(rw,nil)
}

func paramHandler(rw http.ResponseWriter,r*http.Request,p httprouter.Params){
	index := template.Must(template.ParseFiles("public/index.html"))
	//获取页面参数
	chapter := p.ByName("chapter")
	page:= p.ByName("page")

	//从服务器获取数据
	//TODO

	//将HTML发送到页面
	fmt.Printf("\nThe chapter is %s and the page is %s",chapter,page)
	index.Execute(rw,nil)
}

所以基本上,我想根据章节和页面变量提供不同的图像(这不是我当前的问题,但这是我需要URL参数的原因),但路由器认为静态文件路径(我用来提供js和css的路径)充满了参数。我尝试在HTML中的每个路径前面添加"/foo/foo/",但也没有起作用。

这是控制台的示例输出:

从"/":

The chapter is 1 and the page is 1
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

从"/1/2":

The chapter is 1 and the page is 2
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

这里是包含所有文件的存储库,你可以查看我的项目结构。

谢谢!

英文:

So I'm trying to serve static css and java script to an html template, but the parameters are hindering my ability to do so.

here's my code

package main
import (
"net/http"
"html/template"
"github.com/julienschmidt/httprouter"
"fmt"
)
type PageData struct {
Chapter int
Page int
Source string
}
func main(){
//I'm using the julienschmidt router because it has parameters that I can use
//Create a router
router := httprouter.New()
//Create the route with the parameters
router.GET("/:chapter/:page",paramHandler)
//Create the default route last
router.GET("/",defaultHandler)
//get all of the static files working
router.ServeFiles("/:chapter/:page/*filepath",http.Dir("/js/"))
//http.Handle("/js/",http.StripPrefix("/js/",http.FileServer(http.Dir("./public/js/"))))
//http.Handle("/viewjs/",http.StripPrefix("/viewjs/",http.FileServer(http.Dir("./public/viewjs/"))))
//crate a message telling the user which port the server is running on
fmt.Println("Now serving on port 8080")
//Start the server on the specified port
http.ListenAndServe(":8080",router)
}
func defaultHandler(rw http.ResponseWriter,r *http.Request,p httprouter.Params){
//Parse the html file
index := template.Must(template.ParseFiles("public/index.html"))
chapter := 1
page := 1
//Get data from server
//TODO
//Test Data
//defaultPage := PageData{Chapter:chapter,Page:page,Source:"http://lokeshdhakar.com/projects/lightbox2/images/image-4.jpg"}
//Send the html file to the browser
fmt.Printf("\nThe chapter is %d and the page is %d",chapter,page)
index.Execute(rw,nil)
}
func paramHandler(rw http.ResponseWriter,r*http.Request,p httprouter.Params){
index := template.Must(template.ParseFiles("public/index.html"))
//Get the page parameters
chapter := p.ByName("chapter")
page:= p.ByName("page")
//Get data from server
//TODO
//send the html to the page
fmt.Printf("\nThe chapter is %s and the page is %s",chapter,page)
index.Execute(rw,nil)
}

so basically, I want to serve a different image based on the chapter and page variable (That isn't my current problem, but it is the reason I need the url parameters), but the router thinks that the static file path (the one I use to serve js and css) is full of parameters. I tried to just add "/foo/foo/" to the begging of every path in the html, but that didn't work either
Here's a sample output from the console:

from "/"

The chapter is 1 and the page is 1
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

from "/1/2"

The chapter is 1 and the page is 2
The chapter is viewjs and the page is index.js
The chapter is viewjs and the page is index.js

here's the repository with all of my files so you can see my project structure.

Thanks!

答案1

得分: 3

我建议你重新组织你的项目文件结构:

├── main.go
├── templates/
│   ├── index.html
├── assets/
├── js/
└── react/

使用以下处理程序:

router.GET("/", defaultHandler)
router.GET("/chapters/:chapter/pages/:page", paramHandler)
router.ServeFiles("/assets/*filepath", http.Dir("assets"))

并且将你的脚本源文件路径改为包含完整路径,例如:

/assets/js/react/build/react.js

如果httprouter可以匹配以下路由,事情会变得更容易:

router.GET("/:chapter/:page", paramHandler)
router.ServeFiles("/*filepath", http.Dir("assets"))

但是:

> 只有显式匹配: 根据该路由器的设计,一个请求只能精确匹配一个或零个路由。

https://github.com/julienschmidt/httprouter#features

英文:

I would suggest that you restructure your project files

├── main.go
├── templates/
│   ├── index.html
├── assets/
├── js/
└── react/

Use the following handlers

router.GET("/", defaultHandler)
router.GET("/chapters/:chapter/pages/:page", paramHandler)
router.ServeFiles("/assets/*filepath", http.Dir("assets"))

And change your script sources to include the full path, e.g.

/assets/js/react/build/react.js

Things would be a lot easier if httprouter could match routes like

router.GET("/:chapter/:page", paramHandler)
router.ServeFiles("/*filepath", http.Dir("assets"))

But

> Only explicit matches: By design of this router, a request can only match exactly one or no
> route.

https://github.com/julienschmidt/httprouter#features

huangapple
  • 本文由 发表于 2016年2月25日 22:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/35630260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定