Html 在gorilla mux中呈现css js img文件
学习Gorilla工具包和golang,请在这里轻松学习。要在相应的文件夹中呈现.css、.js和.jpeg文件 文件结构为:Html 在gorilla mux中呈现css js img文件,html,css,http,go,gorilla,Html,Css,Http,Go,Gorilla,学习Gorilla工具包和golang,请在这里轻松学习。要在相应的文件夹中呈现.css、.js和.jpeg文件 文件结构为: ROOT/ |--main.go, message.go | |Templates/ | |--index.html,confirmation.html | |Static/ | |css/ |--ex1.css, ex2.css | |js/ |--ex1.js, ex2.js | |Images/
ROOT/
|--main.go, message.go
|
|Templates/
| |--index.html,confirmation.html
|
|Static/
|
|css/
|--ex1.css, ex2.css
|
|js/
|--ex1.js, ex2.js
|
|Images/
|--ex1.jpeg, ex2.jpeg
将带有gorilla pat和mux的main包装如下:
package main
import (
"github.com/gorilla/mux"
"github.com/gorilla/pat"
"html/template"
"log"
"net/http"
)
func main() {
r := pat.New()
r.Get("/", http.HandlerFunc(index))
r.Post("/", http.HandlerFunc(send))
r.Get("/confirmation", http.HandlerFunc(confirmation))
log.Println("Listening...")
http.ListenAndServe(":8080",r)
router := mux.NewRouter()
router.HandleFunc("/", Home)
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/",http.FileServer(http.Dir(./static/))))
http.Handle("/", router)
err := http.ListenAndServe(":8443", router)
if err != nil {
log.Fatalln(err)
}
}
获取错误:
.\main.go:23: syntax error: unexpected .
不知道如何通过func main运行多个http服务器来启动应用程序并呈现嵌套在静态文件夹中的所有文件 你应该:
- 将http.Dir的参数设置为字符串:
http.Dir(“./static/”)
- 使用
命令在单独的Goroutine中运行第一个go
http.listendServe
- 删除行http.Handle(“/”,路由器)。这会将Gorilla Mux路由器注册为
中http.DefaultServeMux
的处理程序,然后您就根本不用它了。因此,它可以安全地移除/
package main
import (
"github.com/gorilla/mux"
"github.com/gorilla/pat"
"log"
"net/http"
)
func main() {
r := pat.New()
r.Get("/", http.HandlerFunc(index))
// etc...
log.Println("Listening on :8080...")
go http.ListenAndServe(":8080", r)
router := mux.NewRouter()
router.HandleFunc("/", home)
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
log.Println("Listening on :8443...")
http.ListenAndServe(":8443", router)
}
func index(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Index page"))
}
func home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Home page"))
}
http.Dir
将字符串作为参数。您需要有http.Dir(“./static”)
。赋值运算符:=
和http.listendServe
之间也没有空格,而且索引和索引处理函数的大小写混合在一起。