Open chenshenhai opened 7 years ago
. ├── server.go ├── static │ ├── css │ │ └── style.css │ └── js │ └── index.js └── template └── index.html
package main import ( "net/http" "html/template" "log" ) // 渲染模板 func render( writer http.ResponseWriter, tplFile string, ctx map[string] string) { tpl, err := template.ParseFiles( tplFile ) if err != nil { http.Error( writer, err.Error(), http.StatusInternalServerError ) return } tpl.Execute( writer, ctx ) } // 主页操作 func indexHandler( writer http.ResponseWriter, req *http.Request ) { context := make(map[string]string) context["title"] = "index page" context["info"] = "this is a go web" render( writer, "template/index.html", context ) return } // main函数 func main() { // 主页 http.HandleFunc("/", indexHandler) // 加载静态资源 http.Handle("/static/js/", http.FileServer(http.Dir("./"))) http.Handle("/static/css/", http.FileServer(http.Dir("./"))) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe:", err.Error()) } }
<html> <head> <title>{{.title}}</title> <link type="text/css" rel="stylesheet" href="/static/css/style.css" /> </head> <body> <div class="box"> <p>{{.info}}</p> </div> <script src="/static/js/index.js"></script> </body> </html>
go run server.go
访问 http://localhost:8080
文件目录
server.go 服务
go语言模板
执行go语言web服务
访问 http://localhost:8080