加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang开发web应用(v0.02)

发布时间:2020-12-16 18:59:46 所属栏目:大数据 来源:网络整理
导读:经过几天实践,现将学习go语言开发web应用的一点经验记录如下: 1、项目管理 可以按go的规范设置,我自己的设置主要为: 其中: hw是项目根目录,是执行文件所在目录;template是模板及静态文件目录,其中有模板文件目录html、css文件目录css、javascript文

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读