在gorilla mux中渲染css js img文件

时间:2014-11-10 18:43:02

标签: html css http go 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/ 
   |--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服务器来启动应用程序并呈现嵌套在静态文件夹中的所有文件。

1 个答案:

答案 0 :(得分:1)

你应该:

  • 将http.Dir的参数设为字符串:http.Dir("./static/")
  • 使用http.ListenAndServe命令在单独的Goroutine中运行第一个go
  • 删除第http.Handle("/", router)行。这会将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"))
}