# API Server

# 创建项目

  • 更新bee go get -u github.com/beego/bee
  • 创建一个beego项目,bee new beeblog
  • 创建数据库,CREATE DATABASE IF NOT EXISTS beeblog DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
  • 创建beegopro.toml
dsn = "root:@tcp(127.0.0.1:3306)/beeblog"
[models.blog]
    names = ["name","content","created_at","updated_at"]
    orms = ["string","string","datetime","datetime"]
    comments = ["名称","内容","创建时间","更新时间"]
[path]
    beego =  "."
1
2
3
4
5
6
7
  • 执行生成脚本,bee pro gen

# Beego添加代码

  • conf/app.conf 增加数据库配置
appname = .
httpport = 8080
runmode = dev

####################MySQL 数据库配置###########################
db_adapter=mysql

# 您的数据库host
db_host="127.0.0.1"

#您的数据库端口
db_port=3306

#您的数据库用户名
db_username="root"

# 您的数据库密码
db_password=""

# utf8或者utf8mb4数据库。如果数据库还没创建,并且账号有创建权限,将自动创建。
db_database="beeblog"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  • main.go 注入数据库代码
package main

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


func main() {
  dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local", beego.AppConfig.String("db_username"), beego.AppConfig.String("db_password"), beego.AppConfig.String("db_host"), beego.AppConfig.String("db_port"), beego.AppConfig.String("db_database"))
  orm.Debug = true
  err := orm.RegisterDataBase("default", "mysql", dataSource)
  if err != nil {
    panic(err)
  }
  beego.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 运行

  • 运行Beego bee run

# 访问

  • 新增 curl -H "Content-Type: application/json" -X POST -d '{"name": "beego pro", "content":"hello beego"}' "http://127.0.0.1:8080/api/blog"
  • 列表 curl http://127.0.0.1:8080/api/blog
  • 详情 curl http://127.0.0.1:8080/api/blog/1
  • 更新 curl -H "Content-Type: application/json" -X PUT -d '{"name": "beego pro", "content":"hello beego pro"}' "http://127.0.0.1:8080/api/blog/1"
  • 删除 curl -H "Content-Type: application/json" -X DELETE "http://127.0.0.1:8080/api/blog/1"