gow 是一个基于gin框架思想和beego框架中html模板处理机制,封装的一个go web框架。可用于开发Web API和Web网站项目。
mkdir hello
cd hello
go mod init
go get github.com/gkzy/gow
package main
import (
"github.com/gkzy/gow"
)
func main() {
r := gow.Default()
r.GET("/", func(c *gow.Context) {
c.JSON(gow.H{
"code": 0,
"msg": "success",
})
})
//default :8080
r.Run()
//r.Run(":9090")
//r.Run("127.0.0.1:9090")
}
go build && ./hello
或
go run main.go
浏览器访问:http://127.0.0.1:8080
curl -i http://127.0.0.1:8080
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Wed, 15 Jul 2020 09:15:31 GMT
Content-Length: 27
{
"code":0,
"msg":"success"
}
包括HTML模板文件处理和静态资源处理
PROJECT_NAME
├──static
├── img
├──111.jpg
├──222.jpg
├──333.jpg
├──js
├──css
├──views
├──index.html
├──article
├──detail.html
├──main.go
r.SetView("views")
r.Static("/static", "static")
main.go
package main
import (
"github.com/gkzy/gow"
)
func main() {
r := gow.Default()
r.AutoRender = true //打开html模板渲染
r.SetView("views") //默认静态目录为views时,可不调用此方法
r.StaticFile("favicon.ico","static/img/log.png") //路由favicon.ico
r.Static("/static", "static")
//router
r.Any("/", IndexHandler)
r.Any("/article/1", ArticleDetailHandler)
//自定义hello的模板函数
//在模板文件可通过 {{hello .string}} 来执行
r.AddFuncMap("hello", func(str string) string {
return "hello:" + str
})
r.Run()
}
//IndexHandler 首页handler
func IndexHandler(c *gow.Context) {
c.HTML("index.html", gow.H{
"name": "gow",
"package": "github.com/gkzy/gow",
})
}
//ArticleDetailHandler 文章详情页handler
func ArticleDetailHandler (c *gow.Context){
c.HTML("article/detail.html", gow.H{
"title": "年薪百万的文科专业有哪些?",
})
}
views/index.html
<html>
<head>
<title>{{hello .name}}</title>
<meta charset="utf-8"/>
</head>
<body>
<h2>{{.name}}</h2>
<hr>
<h5>{{.package}}</h5>
</body>
</html>
views/article/detail.html
<html>
<head>
<title>{{.title}}</title>
<meta charset="utf-8"/>
<style>
img{max-width:600px;}
</style>
</head>
<body>
<h2>{{.title}}</h2>
<hr>
<p><img src="/static/img/111.jpg"></p>
<p><img src="/static/img/222.jpg"></p>
<p><img src="/static/img/333.jpg"></p>
</body>
</html>
go run main.go
或
go build main.go -o app && ./app
https://127.0.0.1:8080/
https://127.0.0.1:8080/article/1