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, 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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值