Golang开发web应用v0.02

经过几天实践,现将学习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 main

import (
	"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,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)

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1&#160;Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...