前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >goframe入坑

goframe入坑

作者头像
是小张啊喂
发布2021-08-09 17:39:40
1.5K0
发布2021-08-09 17:39:40
举报
文章被收录于专栏:软件软件

GoFrame安装

文档地址:https://goframe.org/ 讲的还挺详细的,基本上都能看懂,有语言基础的话基本上就能直接上手了

下载CLI地址:https://github.com/gogf/gf-cli 工具可以帮助我们快速的新建一个GoFrame的项目

GoFrame使用

初始化项目

gf init 项目名 这里有个小问题,默认是不会新建项目名称的文件夹,直接下载依赖代码

项目中的.gitkeep没有用处可以直接删除

Hello World!

启动main.go,访问127.0.0.1:8199 成功!

路由访问

gf 路由 有三种

  1. 函数注册 - 使用BindHandler 方法进行路由注册
  2. 对象注册 - 通过BindObject方法完成执行对象的注册
  3. 控制器注册 - 通过BindController方法完成控制器的注册
代码语言:javascript
复制
// 回调函数注册
func main() {
   s := g.Server()
   s.BindHandler("/", func(r *ghttp.Request) {
       r.Response.Write("Hello World!")
   })
   s.Run()
}
代码语言:javascript
复制
// 执行对象注册
type Controller struct{}

func (c *Controller) Index(r *ghttp.Request) {
    r.Response.Write("index")
}

func (c *Controller) Show(r *ghttp.Request) {
    r.Response.Write("show")
}

func main() {
    s := g.Server()
    c := new(Controller)
    s.BindObject("/object", c)
    s.SetPort(8199)
    s.Run()
}	
代码语言:javascript
复制
type User struct {
    gmvc.Controller
}

func init() {
    s := g.Server()
    s.BindController("/user",                       new(User))
    s.BindController("/user/{.method}/{uid}",       new(User), "Info")
    s.BindController("/user/{.method}/{page}.html", new(User), "List")
}

func (u *User) Index() {
    u.Response.Write("User")
}

func (u *User) Info() {
    u.Response.Write("Info - Uid: ", u.Request.Get("uid"))
}

func (u *User) List() {
    u.Response.Write("List - Page: ", u.Request.Get("page"))
}

这是官方的三个例子,我觉得有点明确,但是有些地方不是很明白。分组路由更为简便易用,下面看下分组路由是如何实现的

代码语言:javascript
复制
func main() {
    s := g.Server()
    group := s.Group("/api")
    group.ALL("/all", func(r *ghttp.Request) {
        r.Response.Write("all")
    })
    group.GET("/get", func(r *ghttp.Request) {
        r.Response.Write("get")
    })
    group.POST("/post", func(r *ghttp.Request) {
        r.Response.Write("post")
    })
    s.SetPort(8199)
    s.Run()
}

这样看来,分组路由觉得是首选,简单易用(主要是可以偷懒)

操作ORM

GoFrame中直接依赖了mysql:https://github.com/go-sql-driver/mysql 内置支持,无需额外扩展或第三方包接入,直接可用 ,其余的需要自己去引入

数据库配置在config/config.toml

代码语言:javascript
复制
# Database.
[database]
    link  = "mysql:root:Root5683@@tcp(127.0.0.1:3306)/myschool"
    debug = true
    # Database logger.
    [database.logger]
        Path   = "/tmp/log/gf-app/sql"
        Level  = "all"
        Stdout = true

gf gen model生成实体之后,下面我们结合上面的路由来看下如何操作数据库

main.go
代码语言:javascript
复制
package router

import (
	"github.com/gogf/gf/frame/g"
	"goframe/app/api/student"
)

func init() {
	s := g.Server()

	s.Group("/", func(group *ghttp.RouterGroup) {
		group.PUT("/save", student.Save)
		group.GET("/select", student.Select)
		group.POST("/update", student.Update)
		group.DELETE("/delete", student.Delete)
	})
}
student.go
代码语言:javascript
复制
package student

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"goframe/app/model/student"
)

// 获取数据库连接
var db = g.DB().Table("student")

// 新增
func Save(r *ghttp.Request) {
	db.Data(student.Entity{
		Id:   r.GetRequestString("id"),
		Name: r.GetRequestString("name"),
		Age:  r.GetRequestInt("age"),
	}).Insert()
	r.Response.WriteJsonExit("新增成功")
}

// 根据id查询
func Select(r *ghttp.Request) {
	stu := (*student.Entity)(nil)
	db.Where("id", r.Get("id")).Struct(&stu)
	r.Response.WriteJsonExit(stu)
}

// 更新
func Update(r *ghttp.Request) {
	db.Data(student.Entity{
		Id:   r.GetRequestString("id"),
		Name: r.GetRequestString("name"),
		Age:  r.GetRequestInt("age"),
	}).Where("id", r.Get("id")).Update()
	r.Response.WriteJsonExit("更新成功")
}

// 删除
func Delete(r *ghttp.Request) {
	db.Where("id", r.Get("id")).Delete()
}

使用Postman测试

PUT:http://127.0.0.1:8199/save

代码语言:javascript
复制
{
    "id":"1",
    "name":"chenghao_",
    "age":"30"
}

POST:http://127.0.0.1:8199/update

代码语言:javascript
复制
{
    "id":"1",
    "name":"ChengHao_",
    "age":"19"
}

http://127.0.0.1:8199/select?id=1

http://127.0.0.1:8199/delete?id=1

sql文件

代码语言:javascript
复制
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `name` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

goframe框架有点像java中的 SpringDataJpa所以更新student.go

代码语言:javascript
复制
// 新增
func Save(r *ghttp.Request) {
	var stu *student.Entity
	if err := r.Parse(&stu); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	db.Data(stu).Insert()
	r.Response.WriteJsonExit("新增成功")
}

// 根据id查询
func Select(r *ghttp.Request) {
	stu := (*student.Entity)(nil)
	db.Where("id", r.Get("id")).Struct(&stu)
	//r.Response.WriteJsonExit(stu)
	r.Response.WriteTpl("index.html", gconv.Map(stu))
}

// 更新
func Update(r *ghttp.Request) {
	var stu *student.Entity
	if err := r.Parse(&stu); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	db.Data(stu).Where("id", stu.Id).Update()
	r.Response.WriteJsonExit("更新成功")
}

// 删除
func Delete(r *ghttp.Request) {
	db.Where("id", r.Get("id")).Delete()
}

新手入门,大佬勿喷,JAVA学习go有点奇怪,很多地方还不是很理解,后续会继续学习更新,共同进步。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • GoFrame安装
  • GoFrame使用
    • 初始化项目
      • Hello World!
        • 路由访问
          • 操作ORM
            • main.go
            • student.go
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档