官术网_书友最值得收藏!

How to do it…

  1. Install the github.com/gorilla/mux package using the go get command, as follows:
$ go get github.com/gorilla/mux
  1. Create serve-static-files-gorilla-mux.go, where we will create a Gorilla Mux router instead of an HTTP FileServer, as follows:
package main
import
(
"html/template"
"log"
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Person struct
{
Id string
Name string
}
func renderTemplate(w http.ResponseWriter, r *http.Request)
{
person := Person{Id: "1", Name: "Foo"}
parsedTemplate, _ := template.ParseFiles("templates/
first-template.html")
err := parsedTemplate.Execute(w, person)
if err != nil
{
log.Printf("Error occurred while executing the template
or writing its output : ", err)
return
}
}
func main()
{
router := mux.NewRouter()
router.HandleFunc("/", renderTemplate).Methods("GET")
router.PathPrefix("/").Handler(http.StripPrefix("/static",
http.FileServer(http.Dir("static/"))))
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Run the program with the following command:
$ go run serve-static-files-gorilla-mux.go
主站蜘蛛池模板: 兴文县| 吴旗县| 葫芦岛市| 定西市| 唐山市| 晋城| 海城市| 博野县| 克东县| 屏东县| 凭祥市| 老河口市| 新安县| 卢湾区| 冀州市| 独山县| 阜新市| 宣武区| 洛扎县| 寿宁县| 桐乡市| 广德县| 留坝县| 大城县| 漯河市| 永宁县| 辽中县| 石渠县| 务川| 安吉县| 海阳市| 自贡市| 吉木萨尔县| 西充县| 和田县| 开鲁县| 板桥市| 德阳市| 石门县| 岳普湖县| 伊宁县|