go语言 有很多优秀的web框架,于是乎,就自己动手 从零开始搭建一个demo,除了有些东西下载比较麻烦,其它的都很好弄,下面贴出我搭建的工程.在开始项目之前需要下载并安装好go的环境以及iris还有gorm的环境.
一:首先贴出我的项目结构图:
二:各分层情况代码
controlle层
-
package controllers
-
-
import (
-
"github.com/kataras/iris/context"
-
"github.com/spf13/cast"
-
"iris_demo/models"
-
"iris_demo/service"
-
"log"
-
)
-
-
type UserController
struct {
-
Service service.UserService
-
}
-
func NewUserController() *UserController {
-
return &UserController{Service:service.NewUserService()}
-
}
-
//查询所有
-
func (self *UserController) GetList()(result *models.Result) {
-
return self.Service.GetUserList()
-
}
-
-
//保存 and 修改
-
func (self *UserController) PostSaveUser(ctx context.Context)(result models.Result) {
-
user :=
new(models.User)
-
err := ctx.ReadForm(user)
-
if err !=
nil{
-
log.Println(err)
-
result.Msg =
"数据有错误"
-
return
-
}
-
return self.Service.PostSaveUser(*user)
-
}
-
-
//根据id查询
-
func (self *UserController) GetUserById(ctx context.Context)(result models.Result) {
-
id := ctx.PostValue(
"id")
-
if id ==
"" {
-
result.Code =
400
-
result.Msg =
"缺少参数id"
-
return
-
}
-
return self.Service.GetUserById(cast.ToUint(id))
-
}
-
-
//根据id删除
-
func (self *UserController) PostDelUser(ctx context.Context)(result models.Result) {
-
id := ctx.PostValue(
"id")
-
if id ==
"" {
-
result.Code =
400
-
result.Msg =
"缺少参数id"
-
return
-
}
-
return self.Service.DelUser(cast.ToUint(id))
-
}
service层
-
package service
-
-
import (
-
"iris_demo/models"
-
"iris_demo/repo"
-
)
-
type UserService
interface {
-
GetUserList () *models.Result
-
PostSaveUser(user models.User) (result models.Result)
-
GetUserById(id
uint) (result models.Result)
-
DelUser(id
uint) (result models.Result)
-
}
-
-
type userService
struct {}
-
-
func NewUserService() UserService{
-
return &userService{}
-
}
-
-
var userRepo = repo.NewUserRepository()
-
-
func (self userService)GetUserList() *models.Result{
-
books := userRepo.GetUserList()
-
result :=
new (models.Result)
-
result.Data = books
-
result.Code =
200
-
result.Msg =
"SUCCESS"
-
return result
-
}
-
func (self userService) PostSaveUser(user models.User)(result models.Result){
-
err := userRepo.SaveUser(user)
-
if err !=
nil{
-
result.Code =
400
-
result.Msg = err.Error()
-
}
else{
-
result.Code =
200
-
result.Msg =
"SUCCESS"
-
user := userRepo.GetUserByName(user.Name)
-
result.Data = user
-
}
-
return
-
}
-
func (self userService) GetUserById(id uint)(result models.Result){
-
user,err := userRepo.GetUserById(id)
-
if err!=
nil{
-
result.Code =
400
-
result.Msg = err.Error()
-
}
else{
-
result.Data = user
-
result.Code =
200
-
result.Msg =
"SUCCESS"
-
}
-
return result
-
}
-
func (self userService) DelUser(id uint)(result models.Result){
-
err := userRepo.DeleteUser(id)
-
if err!=
nil{
-
result.Code =
400
-
result.Msg = err.Error()
-
}
else{
-
result.Code =
200
-
result.Msg =
"SUCCESS"
-
list := userRepo.GetUserList()
-
result.Data = list
-
-
}
-
return
-
}
-
Repository层
-
package repo
-
-
import (
-
"iris_demo/datasource"
-
"iris_demo/models"
-
)
-
type UserRepository
interface {
-
GetUserList() *[]models.User
-
SaveUser(book models.User)(err error)
-
GetUserById(id
uint)(book models.User,err error)
-
DeleteUser(id
uint)(err error)
-
GetUserByName(name
string )*[]models.User
-
}
-
func NewUserRepository() UserRepository{
-
return &userRepository{}
-
}
-
var db = datasource.GetDB()
-
-
type userRepository
struct {}
-
-
func (self userRepository) GetUserList()*[]models.User{
-
user:=
new([]models.User)
-
err:=db.Raw(
`select * FROM user`).Scan(user).RowsAffected
-
if err >
0 {
-
return user
-
}
else{
-
return
nil
-
}
-
}
-
func (self userRepository)GetUserByName(name string )*[]models.User{
-
user:=
new([]models.User)
-
err:=db.Raw(
`select * FROM user where user.name = ?`,name).Scan(user).RowsAffected
-
if err >
0 {
-
return user
-
}
else{
-
return
nil
-
}
-
}
-
-
-
func (self userRepository) SaveUser(user models.User)(err error){
-
if user.ID !=
0{
-
err := db.Save(&user).Error
-
return err
-
}
else {
-
err := db.Create(&user).Error
-
return err
-
}
-
}
-
func (self userRepository) GetUserById(id uint)(user models.User,err error){
-
err = db.First(&user,id).Error
-
return user,err
-
}
-
func (self userRepository) DeleteUser(id uint)(err error){
-
user:=
new(models.User)
-
user.ID = id
-
err = db.Unscoped().Delete(&user).Error
-
return err
-
}
-
入口main 方法
-
package main
-
-
import (
-
"flag"
-
"github.com/kataras/iris"
-
"iris_demo/conf"
-
"iris_demo/route"
-
)
-
-
func main() {
-
flag.Parse()
-
app := newApp()
-
route.InitRouter(app)
-
err := app.Run(iris.Addr(
":"+conf.Sysconfig.Port), iris.WithoutServerError(iris.ErrServerClosed))
-
if err !=
nil {
-
panic(err)
-
}
-
}
-
-
func newApp() *iris.Application {
-
app := iris.New()
-
app.Configure(iris.WithOptimizations)
-
app.AllowMethods(iris.MethodOptions)
-
return app
-
}
model
user
-
package models
-
-
type User
struct {
-
ID
uint
`gorm:"primary_key"`
-
Name
string
`gorm:"type:varchar(20);not null;"`
-
Age
string
`gorm:"type:varchar(10);not null;"`
-
Sex
string
`gorm:"type:varchar(20);not null;"`
-
}
-
-
Result
-
package models
-
-
type Result
struct {
-
Code
int
-
Msg
string
-
Data
interface{}
-
}
-
-
func NewResult(data interface{}, c int, m ...string) *Result {
-
r := &Result{Data: data, Code: c}
-
-
if e, ok := data.(error); ok {
-
if m ==
nil {
-
r.Msg = e.Error()
-
}
-
}
else {
-
r.Msg =
"SUCCESS"
-
}
-
if
len(m) >
0 {
-
r.Msg = m[
0]
-
}
-
-
return r
-
}
初始化表
-
package datasource
-
-
import (
-
"iris_demo/models"
-
)
-
// 初始化表 如果不存在该表 则自动创建
-
func Createtable() {
-
GetDB().AutoMigrate(
-
&models.User{},
-
)
-
}
数据库连接
-
package datasource
-
-
import (
-
_
"github.com/go-sql-driver/mysql"
-
"github.com/jinzhu/gorm"
-
"iris_demo/conf"
-
"strings"
-
"time"
-
)
-
-
var db *gorm.DB
-
-
func GetDB() *gorm.DB {
-
return db
-
}
-
-
func init() {
-
path := strings.Join([]
string{conf.Sysconfig.DBUserName,
":", conf.Sysconfig.DBPassword,
"@(", conf.Sysconfig.DBIp,
":", conf.Sysconfig.DBPort,
")/", conf.Sysconfig.DBName,
"?charset=utf8&parseTime=true"},
"")
-
var err error
-
db, err = gorm.Open(
"mysql", path)
-
if err !=
nil{
-
panic(err)
-
}
-
db.SingularTable(
true)
-
db.DB().SetConnMaxLifetime(
1 * time.Second)
-
db.DB().SetMaxIdleConns(
20)
//最大打开的连接数
-
db.DB().SetMaxOpenConns(
2000)
//设置最大闲置个数
-
db.SingularTable(
true)
//表生成结尾不带s
-
// 启用Logger,显示详细日志
-
db.LogMode(
true)
-
Createtable();
-
}
路由设置
-
package route
-
-
import (
-
"github.com/kataras/iris"
-
"github.com/kataras/iris/mvc"
-
"iris_demo/controllers"
-
)
-
-
func InitRouter(app *iris.Application) {
-
bathUrl :=
"/api"
-
mvc.New(app.Party(bathUrl +
"/user")).Handle(controllers.NewUserController())
-
}
数据库参数设置 config.json
-
{
-
"Port":
"端口",
-
"DBUserName":
"root",
-
"DBPassword":
"数据库密码",
-
"DBIp":
"数据库地址",
-
"DBPort":
"3306",
-
"DBName":
"数据库Name"
-
}
配置config
-
package conf
-
-
import (
-
"github.com/json-iterator/go"
-
"io/ioutil"
-
)
-
-
var Sysconfig = &sysconfig{}
-
-
func init() {
-
//指定对应的json配置文件
-
b, err := ioutil.ReadFile(
"config.json")
-
if err !=
nil {
-
panic(
"Sys config read err")
-
}
-
err = jsoniter.Unmarshal(b, Sysconfig)
-
if err !=
nil {
-
panic(err)
-
}
-
-
}
-
-
type sysconfig
struct {
-
Port
string
`json:"Port"`
-
DBUserName
string
`json:"DBUserName"`
-
DBPassword
string
`json:"DBPassword"`
-
DBIp
string
`json:"DBIp"`
-
DBPort
string
`json:"DBPort"`
-
DBName
string
`json:"DBName"`
-
-
}
-
启动项目,第一次启动会自动给我们创建表,我们可以通过控制台看到日志
三:测试
添加数据
在查看数据库,可以看到数据插入成功
修改数据
数据库
根据ID查询
查询所有(为了看到效果 我在插入一条)
根据ID删除数据(删除之后 我们在查询所有 会发现我们那条数据已经被删除掉了)
查看数据库发现只有一条了
到此,简单的增删改查已经全部完成.
转载:https://blog.csdn.net/FindHuni/article/details/105709378
查看评论