gow,另外一个golang web 框架

Golang 归档:202007
普通
浏览:4356
2020-07-21 10:34:01
gow 是自我封装的另外一个golang web框架,正在逐步扩展中。目的是做到适合自己使用就够了。

注意:请使用 https://22v.net/article/3262/

gow 是一个基于gin框架思想和beego框架中html模板处理机制,封装的一个go web框架。可用于开发Web API和Web网站项目。

项目地址:

https://github.com/gkzy/gow

官网地址:

https://gow.22v.net


快速开始

mkdir hello
cd hello
go mod init
go get github.com/gkzy/gow
创建 main.go
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
注意事项
  • 此文章对你有帮助,对作者表示感谢(微信):
  • 本文地址:https://22v.net/article/3259/
  • 转载本文时,请注明转载自“SamBlog”的字样。
  • 如此文章有损您的合法权益,请使用页面底部的邮箱与我取得联系。
分类目录
文章归档
友情站点