1 Star 2 Fork 0

haming123 / wego

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

简介

wego是一个Go语言编写的高性能的Web框架,可以用来快速开发RESTful服务以及后端服务等各种应用。 wego框架包括:路由模块、ORM模块、websocket模块、session模块等模块。具体特征如下:

  1. 基于Radix树开发的路由模块,路由查询性能高。
  2. 支持混合路由,固定路由、参数路由、前缀路由可以混合,不冲突。
  3. 支持路由组,可以为不同层次的路由设置过滤器中间件。
  4. 为路由参数、Query参数、Form参数的访问提供率方便易于使用的API,并可以将参数映射到Struct。
  5. 为JSON、XML和HTML渲染提供了易于使用的API。
  6. 支持过滤器中间件,方便您对Web框架进行扩展。
  7. 支持BeforeRoute、BeforeExec、AfterExec拦截器,方便您进行身份验证、日志输出。
  8. 支持Crash处理机制,wego可以recover一个HTTP请求中的panic,这样可确保您的服务器始终可用。
  9. 内置Session模块,您可以选择cookie、redis、memcache、memory缓存引擎存储Session数据。
  10. 内置ORM模块,使用方便,功能强大。
  11. 内置websocket模块,采用更加经济的内存分配机制,使得每台服务器可接入更多的客户端。
  12. 内置配置模块,方便对应用的参数进行管理。
  13. 内置高性能LOG模块,支持日志分级,支持按照天轮换日志文件。
  14. 采用缓存来管理HTML的Template,既方便输出Html页面,又可以使用缓存提升系统性能。

安装

go get github.com/haming123/wego

使用文档

请点击:详细文档

简单http server

创建一个main.go文件,代码如下:

package main
import (
	"github.com/haming123/wego"
	log "github.com/haming123/wego/dlog"
)
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/hello", func(c *wego.WebContext) {
		c.WriteText(200, "world")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

然后运行它,打开浏览器,输入http://localhost:8080/hello, 就可以看到如下内容:

world

项目结构

wego框没有对项目结构做出限制,这里给出一个MVC框架项目的建议结构:

demo
├── app             
│   └── router.go       - 路由配置文件
│   └── templfun.go     - 模板函数文件
├── controllers         - 控制器目录,必要的时候可以继续划分子目录
│   └── controller_xxx.go
├── models              - 模型目录
│   └── model_xxx.go
├── logs                - 日志文件目录,主要保存项目运行过程中产生的日志
│   └── applog_20211203.log
├── static              - 静态资源目录
│   ├── css
│   ├── img
│   └── js
├── utils               - 公共代码目录
│   └── util_xxx.go
├── views               - 视图模板目录
│   └── html_xxx.html
├── app.conf            - 应用配置文件
└── main.go             - 入口文件

注册参数路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/user/:id", func(c *wego.WebContext) {
		c.WriteTextF(200, "param id=%s", c.RouteParam.GetString("id").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

注册模糊匹配路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/files/*name", func(c *wego.WebContext) {
		c.WriteTextF(200, "param name=%s", c.RouteParam.GetString("name").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

注册RESTful路由

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/users/:id", func(c *wego.WebContext) {
		//查询一个用户
	})
	web.POST("/users/:id", func(c *wego.WebContext) {
		//创建一个用户
	})
	web.PUT("/users/:id", func(c *wego.WebContext) {
		//更新用户信息
	})
	web.PATCH("/users/:id", func(c *wego.WebContext) {
		//更新用户的部分信息
	})
	web.DELETE("/users/:id", func(c *wego.WebContext) {
		//删除用户
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

获取参数

在wego中通过c.Param.GetXXX函数来获取请求参数:

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			t.Error(name.Error)
		}
		age := c.Param.GetInt("age")
		if age.Error != nil {
			t.Error(age.Error)
		}
        c.WriteText(200, name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用MustXXX便捷函数获取参数

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.MustString("name")
		t.Log(name)
		age := c.Param.MustInt("age")
		t.Log(age)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用ReadJSON获取参数

若POST请求中Body的数据的格式为JSON格式,可以直接使用WebContext的ReadJSON函数来读取:

func main() {
   web, err := wego.NewWeb()
   if err != nil{
   	log.Error(err)
   	return
   }

   web.POST("/user", func(c *WebContext) {
   	var user2 User
   	err := c.ReadJSON(&user2)
   	if err != nil {
   		t.Log(err)
   	}
   	t.Log(user2)
   })

   err = web.Run(":8080")
   if err != nil {
   	log.Error(err)
   }
}

输出JSON数据

wego对于JSON的支持非常好,可以让我们非常方便的开发一个基于JSON的API。若要返回JSON请求结果,您可以使用WriteJSON函数:

func writeJson(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteJSON(200, user)
}

输出HTML数据

wego框架的html结果的输出是基于html/template实现的。以下是一个输出html页面的例子:

func writeHtml(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteHTML(200, "./views/index.html", user)
}

使用模板函数

如果您的模板文件中使用了模板函数,需要预先将所需的模板函数进行登记:

func GetUserID(id int64) string {
	return fmt.Sprintf("ID_%d", id)
}

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	wego.AddTemplFunc("GetUserID", GetUserID)
	web.GET("/templfunc", (c *wego.WebContext) {
        var user User
        user.ID = 1
        user.Name = "lisi"
        user.Age = 12
        c.WriteHTML(200, "./views/index.html", user)
     })

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

设置cookie

func setCookie(c *wego.WebContext)  {
	val, err := c.Input.Cookie("demo")
	if err != nil {
		log.Error(err)
	}
	cookie := &http.Cookie{
		Name:     "demo",
		Value:    "test",
		Path:     "/",
		HttpOnly: true,
	}
	c.SetCookie(cookie)
}

重定向

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/redirect", func(c *wego.WebContext) {
		c.Redirect(302, "/index")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

错误处理

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/abort", func(c *wego.WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			c.AbortWithError(500, name.Error)
			return
		}
		c.WriteText(200, "hello " + name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

使用配置文件

  • 首先定义一个简单的配置文件
#应用名称
app_name = demo
#mysql数据库的配置参数
mysql = root:rootpwd@tcp(127.0.0.1:3306)/demp?charset=utf8

[server]
#http监听端口
http_port = 8080
  • 使用InitWeb()函数初始化Web服务器
func main() {
    web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

说明:调用InitWeb()函数时可以指定一个配置文件,若没有指定配置文件,则使用缺省的配置文件:./app.conf。

获取业务参数

调用InitWeb()后wego会自动将系统参数解析到WebEngine.Config中,业务参数则需要用户自己调用配置数据的GetXXX函数来获取。例如:

func main() {
	web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	mysql_cnn := web.Config.GetString("mysql")
	if mysql_cnn.Error != nil {
		log.Error(mysql_cnn.Error)
		return
	}
	log.Info(mysql_cnn.Value)

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

使用Session

  • 首选定义配置文件:
#应用名称
app_name = demo

[server]
#http监听端口
http_port = 8080

[session]
#session 是否开启
session_on = true
#session类型:cookie、cache
session_store=cookie
#客户端的cookie的名称
cookie_name = "wego"
#session 过期时间, 单位秒
life_time = 3600
#session数据的hash字符串
hash_key = demohash
  • 然后在入口函数中加载配置文件
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/login", login)
	web.GET("/index", index)

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}
  • 然后再login处理器函数中保存session数据:
func login(c *wego.WebContext)  {
	c.Session.Set("uid", 1)
	c.Session.Save()
	c.Redirect(302, "/index")
}
  • 然后index处理器函数中就可以访问session数据了:
func index(c *wego.WebContext)  {
	id , _ := c.Session.GetInt("uid")
	c.WriteTextF(200, "uid=%d", id)
}

输出日志

package main
import log "wego/dlog"
func main()  {
	log.Debug("This is a Debug Message")
	log.Info("This is a Info Message")
}
//执行后的输出结果为:
//2021/11/30 07:20:06 [D] main.go:31 This is a Debug Message
//2021/11/30 07:20:06 [I] main.go:32 This is a Debug Info
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

wego是一个Go语言编写的高性能的Web框架,可以用来快速开发RESTful服务以及后端服务等各种应用。 wego框架包括:路由模块、ORM模块、websocket模块、session模块等模块。 展开 收起
Go 等 2 种语言
Apache-2.0
取消

发行版 (1)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Go
1
https://gitee.com/haming123/wego.git
git@gitee.com:haming123/wego.git
haming123
wego
wego
main

搜索帮助