這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
經過幾天實踐,現將學習go語言開發web應用的一點經驗記錄如下:
1、專案管理
可以按go的規範設定,我自己的設定主要為:
其中:
hw是項目根目錄,是執行檔案所在目錄;template是模板及靜態檔案目錄,其中有模板檔案目錄html、css檔案目錄css、javascript檔案目錄等,其它如image等根據需要設定。
2、如何設定模板及靜態檔案目錄?
如下代碼,利用http的Dir、FileServer、StripPrefix、Handle函數進行設定:
func StaticServer(prefix string, staticDir string) {http.Handle(prefix, http.StripPrefix(prefix, http.FileServer(http.Dir(staticDir))))return}使用樣本:
StaticServer("/template/", "./template")其中
"./template"是相對目錄或絕對目錄,如本例中為"hw/template"或"d:/hw/template";
"/template/"是URL中的路徑名稱,如:http://www.google.com/template 。
在HTML檔案或其它函數中如何使用呢?
HTML中:
<link rel="stylesheet" href="template/css/main.css" type="text/css" />
函數中:
if r.Method == "GET"{t,err := template.ParseFiles("template/html/homepage.html")if err != nil{return}3、完整範例程式碼:
Go原始碼:
package mainimport ("log""net/http""html/template")func Hello(w http.ResponseWriter, r *http.Request) {if r.Method == "GET"{t,err := template.ParseFiles("template/html/homepage.html")if err != nil{return}err = t.Execute(w, nil)}}func StaticServer(prefix string, staticDir string) {http.Handle(prefix, http.StripPrefix(prefix, http.FileServer(http.Dir(staticDir))))return}func main() {StaticServer("/template/", "./template")http.HandleFunc("/", Hello)err := http.ListenAndServe(":8000", nil)if err != nil {log.Fatal("ListenAndServe: ", err.Error())}}
CSS原始碼:
body{ background-color: black; color: red; text-align: center;}
HTML原始碼:
<html> <head> <title>okkkkkk</title> <link rel="stylesheet" href="template/css/main.css" type="text/css" /> </head> <body> <h2>this is a test for golang.</h2> </body></html>
4、編譯運行:
1)8g hw.go
2)8l -o hw.exe hw.8
3)hw
5、運行結果:
原始碼見我的資源中:http://download.csdn.net/detail/yavobo/5783049 (v0.02) 和http://download.csdn.net/detail/yavobo/5786411 (v0.03)