Golang開發web應用(v0.02)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

經過幾天實踐,現將學習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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.