Golang开发web应用(v0.02)

yavobo · · 1411 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:yavobo

查看原文:Golang开发web应用(v0.02)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1411 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传