栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go语言——教你分分钟用beego框架写一个接口

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go语言——教你分分钟用beego框架写一个接口

一、创建项目

使用bee工具创建一个项目test

bee new test

结果:

二、数据库创建

navicat打开数据库新建一个,数据库名test,表明example,字段如下:

添加两条数据:

三、代码

代码使用goland打开
1、models下新建test.go文件
代码如下:

package models

import (
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Example struct {
	Id int
	Name string
	Message string
	Age int
}

func init()  {
	// root 用户名,123456 密码,127.0.0.1 数据库ip,3306 数据库端口
	orm.RegisterDataBase("default","mysql","root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
	orm.RegisterModel(new(Example))
}

这个时候 _ “github.com/go-sql-driver/mysql” 这行代码会标红,原因是没有安装ORM,那我们就安装一下ORM,cmd进入项目根目录,执行代码如下:

go get github.com/astaxie/beego/orm

执行完后,关闭goland重新打开代码即可,

2、controllers下新建test.go文件
代码如下:

package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type TestController struct {
	beego.Controller
}

type JSONS struct {
	Code int
	Msg string
	Data []orm.Params
}

func (c *TestController) Get() {
	o := orm.NewOrm()
	var example1 []orm.Params
	example, err := o.QueryTable("example").Filter("name","张三").Values(&example1,"id","message","age")
	if err == nil {
		fmt.Printf("Result Nums: %dn", example)
		data := &JSONS{200,"请求成功",example1}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

3、routers文件加下router.go文件中添加路由,
代码如下:

package routers

import (
	"github.com/astaxie/beego"
	"test/controllers"
)

func init() {
    beego.Router("/", &controllers.MainController{})
	beego.Router("/test",&controllers.TestController{})
}

4、main.go添加执行models的初始化方法
代码如下:

package main

import (
	_ "test/routers"
	_ "test/models"
	"github.com/astaxie/beego"
)

func main() {
	beego.Run()
}
四、运行

cmd进入项目test根目录,bee run运行项目
访问127.0.0.1:8080/test,成功!结果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号