go语言web开发模板引擎基础

go语言web开发模板引擎基础

go语言qingyu2022-02-24 16:15:50867A+A-

1.png2.png

package main

import (
   "fmt"
   "github.com/gorilla/mux"
   "html/template" //模板包
   "net/http"
)

//申明模板变量,自动引入模板包
var templates *template.Template

func main() {
   templates = template.Must(template.ParseGlob("templates/*.html"))
   r := mux.NewRouter()
   //普通路由
   r.HandleFunc("/", indexHandler)
   r.HandleFunc("/admin", adminHandler)

   http.ListenAndServe(":8080", r)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
   w.WriteHeader(http.StatusOK)
   templates.ExecuteTemplate(w, "index.html", nil)
}
func adminHandler(w http.ResponseWriter, r *http.Request) {
   w.WriteHeader(http.StatusOK)
   fmt.Fprintf(w, "<h1>后台</h1>")
}
点击这里复制本文地址 欢迎来到大黄鸡源码分享网
qrcode

大黄鸡源码编程网 © All Rights Reserved.  
网站备案号:闽ICP备18012015号-4
Powered by Z-BlogPHP
联系我们| 关于我们| 广告联系| 网站管理