0

0

使用 Goravel 进行 CRUD 操作 (Laravel for GO)

聖光之護

聖光之護

发布时间:2024-10-08 13:25:50

|

1124人浏览过

|

来源于dev.to

转载

使用 goravel 进行 crud 操作 (laravel for go)

关于goravel

goravel是一个功能齐全、扩展性极佳的web应用框架,作为入门脚手架,帮助gopher快速构建自己的应用。

goravel 是针对 go 开发人员的 laravel 的完美克隆,这意味着像我这样的 php 开发人员可以轻松地与该框架建立联系并开始编写,几乎不需要学习。

下面开始安装,您可以按照本文安装或访问goravel官方文档网站。

// download framework
git clone https://github.com/goravel/goravel.git && rm -rf goravel/.git*

// install dependencies
cd goravel && go mod tidy

// create .env environment configuration file
cp .env.example .env

// generate application key
go run . artisan key:generate

//start the application
go run .

在你最喜欢的文本编辑器中打开代码,你会看到项目结构与 laravel 完全一样,所以 laravel 开发者不会感到如此迷失。

模型、迁移和控制器

要创建模型、迁移和控制器,我们可以使用 artisan 命令,就像在 laravel 中一样。

// create model 
go run . artisan make:model category

// create migration 
go run . artisan make:migration create_categories_table

// create controller 
go run . artisan make:controller --resource category_controller

现在,如果我们检查数据库/迁移文件夹,我们将看到已经为我们创建了文件,向上和向下文件,打开向上迁移文件并将以下代码粘贴到其中:

create table categories (
  id bigint(20) unsigned not null auto_increment,
  name varchar(255) not null,
  created_at datetime(3) not null,
  updated_at datetime(3) not null,
  primary key (id),
  key idx_categories_created_at (created_at),
  key idx_categories_updated_at (updated_at)
) engine = innodb default charset = utf8mb4;ngine = innodb default charset = utf8mb4;

如果我们检查app/http/controllers文件夹中,我们将有一个category_controller.go文件,里面的内容应该如下所示:

package controllers

import (
 "github.com/goravel/framework/contracts/http"
)

type categorycontroller struct {
 //dependent services
}

func newcategorycontroller() *categorycontroller {
 return &categorycontroller{
  //inject services
 }
}

func (r *categorycontroller) index(ctx http.context) http.response {
 return nil
} 

func (r *categorycontroller) show(ctx http.context) http.response {
 return nil
}

func (r *categorycontroller) store(ctx http.context) http.response {
 return nil
}

func (r *categorycontroller) update(ctx http.context) http.response {
 return nil
}

func (r *categorycontroller) destroy(ctx http.context) http.response {
 return nil
}

然后,让我们在 app/http/model 中找到类别模型文件,然后将以下代码粘贴到其中:

package models

import (
 "github.com/goravel/framework/database/orm"
)

type category struct {
 orm.model
 name string
}

这里没有发生什么,我们只是用他们的数据类型声明我们的可填充。

让我们在路由文件夹中找到 api.php 文件并将代码更新为如下所示:

package routes

import (
 "github.com/goravel/framework/facades"

 "goravel/app/http/controllers"
)

func api() {
 usercontroller := controllers.newusercontroller()
 facades.route().get("/users/{id}", usercontroller.show)

 //resource route
 categorycontroller := controllers.newcategorycontroller()
 facades.route().resource("/category", categorycontroller)
}

现在,让我们更新category_controller.go 文件中的导入并将其更新为以下内容:

import (
 "goravel/app/models"
 "github.com/goravel/framework/contracts/http"
  "github.com/goravel/framework/facades"
)

我们刚刚导入了模型和门面,门面让我们能够访问很多很酷有用的东西,比如验证、orm 等。orm 是 go 的 orm。

MedPeer科研绘图
MedPeer科研绘图

生物医学领域的专业绘图解决方案,告别复杂绘图,专注科研创新

下载

是时候编写一些代码了!

让我们将控制器中的方法更新为以下代码:

索引方法

// this is just to pull all categories in our database
func (r *categorycontroller) index(ctx http.context) http.response {
 var categories []models.category

 if err := facades.orm().query().find(&categories); err != nil {
  return ctx.response().json(http.statusinternalservererror, http.json{
   "error": err.error(),
  })
 }

 return ctx.response().success().json(http.json{
  "success": true,
  "message": "data fetch successfully",
  "data":    categories,
 })
} 

储存方法

func (r *categorycontroller) store(ctx http.context) http.response {

// validate the input name that the user is passing
 validation, err := facades.validation().make(ctx.request().all(), map[string]string{
        "name": "required|string",
    })

// check if an error occured, might not be validation error
    if err != nil {
        return ctx.response().json(http.statusinternalservererror, http.json{
            "success": false,
            "message": "validation setup failed",
            "error":   err.error(),
        })
    }

// check for validation errors
    if validation.fails() {
        return ctx.response().json(http.statusbadrequest, http.json{
            "success": false,
            "message": "validation failed",
            "errors":  validation.errors().all(),
        })
    }

// create the category
 category := &models.category{
  name: ctx.request().input("name"),
 }

// save the category and return error if there is any
 if err := facades.orm().query().create(category); err != nil {
  return ctx.response().json(http.statusinternalservererror, http.json{
   "success": false,
   "errors": err.error(),
  })
 }

// upon successfull creation return success response with the newly created category
 return ctx.response().success().json(http.json{
  "success": true,
  "message": "category created successfully",
  "data":    category,
 })
}

更新方法

func (r *categorycontroller) update(ctx http.context) http.response {

    validation, err := facades.validation().make(ctx.request().all(), map[string]string{
        "id":   "required",
        "name": "required|string",
    })

    if err != nil {
        return ctx.response().json(http.statusinternalservererror, http.json{
            "success": false,
            "message": "validation setup failed",
            "error":   err.error(),
        })
    }

    if validation.fails() {
        return ctx.response().json(http.statusbadrequest, http.json{
            "success": false,
            "message": "validation failed",
            "errors":  validation.errors().all(),
        })
    }

// find the category using the id
    var category models.category
    if err := facades.orm().query().where("id", ctx.request().input("id")).first(&category); err != nil {
        return ctx.response().json(http.statusnotfound, http.json{
            "success": false,
            "message": "category not found",
        })
    }

// update or return error if there is any
    category.name = ctx.request().input("name")
    if err := facades.orm().query().save(&category); err != nil {
        return ctx.response().json(http.statusinternalservererror, http.json{
            "success": false,
            "message": "failed to update category",
            "error":   err.error(),
        })
    }

// return success if successfull
    return ctx.response().success().json(http.json{
        "success": true,
        "message": "category updated successfully",
        "data":    category,
    })
}

销毁方法

func (r *categorycontroller) destroy(ctx http.context) http.response {

// find the category by id
 var category models.category
 facades.orm().query().find(&category, ctx.request().input("id"))
 res, err := facades.orm().query().delete(&category)

// return error if there is any
 if err != nil {
  return ctx.response().json(http.statusinternalservererror, http.json{
  "error": err.error(),
  })
 }

// return success if successfull
 return ctx.response().success().json(http.json{
  "success": true,
  "message": "category deleted successfully",
  "data":    res,
 })
}

现在我们需要设置数据库,我将使用 mysql,重要的是要注意 gravel 附带了多个数据库驱动程序。找到您的 .env 文件并编辑以下行:

db_connection=mysql
db_host=127.0.0.1
db_port=3306
db_database=database_name
db_username=database_username
db_password=database_password

然后在您的终端中输入:

go run . artisan migrate

这将自动迁移数据库中的类别表。

现在,如果您之前正在运行我们的服务器,我们需要停止它并重新启动它。

您现在可以从 postman 测试您的端点,您应该注意,通过将资源添加到类别端点,您现在可以访问类别端点的 get、post、put 或 delete 方法。您可以通过以下方式访问您的端点:

// GET category
http://localhost:3000/category

//POST catgory - with payload
http://localhost:3000/category
{
    "name": "goravel"
}

// PUT category - with payload
http://localhost:3000/category/{id}
{
    "id": 1,
    "name": "laravel"
}

//DELETE category
http://localhost:3000/category/{id}

这就是如何使用 goravel 进行简单的 crud 操作。

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

2740

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

1671

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

1530

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

995

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

1464

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

1235

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1549

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1307

2023.11.13

AO3中文版入口地址大全
AO3中文版入口地址大全

本专题整合了AO3中文版入口地址大全,阅读专题下面的的文章了解更多详细内容。

1

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
MySQL 教程
MySQL 教程

共48课时 | 1.8万人学习

MySQL 初学入门(mosh老师)
MySQL 初学入门(mosh老师)

共3课时 | 0.3万人学习

简单聊聊mysql8与网络通信
简单聊聊mysql8与网络通信

共1课时 | 805人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号