关于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。
是时候编写一些代码了!
让我们将控制器中的方法更新为以下代码:
索引方法
// 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 操作。
以上是使用 Goravel 进行 CRUD 操作 (Laravel for GO)的详细内容。更多信息请关注PHP中文网其他相关文章!

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

Golang适合快速开发和并发编程,而C 更适合需要极致性能和底层控制的项目。1)Golang的并发模型通过goroutine和channel简化并发编程。2)C 的模板编程提供泛型代码和性能优化。3)Golang的垃圾回收方便但可能影响性能,C 的内存管理复杂但控制精细。

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。

C 更适合需要直接控制硬件资源和高性能优化的场景,而Golang更适合需要快速开发和高并发处理的场景。1.C 的优势在于其接近硬件的特性和高度的优化能力,适合游戏开发等高性能需求。2.Golang的优势在于其简洁的语法和天然的并发支持,适合高并发服务开发。

Golang在实际应用中表现出色,以简洁、高效和并发性着称。 1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Go语言的核心特性包括垃圾回收、静态链接和并发支持。1.Go语言的并发模型通过goroutine和channel实现高效并发编程。2.接口和多态性通过实现接口方法,使得不同类型可以统一处理。3.基本用法展示了函数定义和调用的高效性。4.高级用法中,切片提供了动态调整大小的强大功能。5.常见错误如竞态条件可以通过gotest-race检测并解决。6.性能优化通过sync.Pool重用对象,减少垃圾回收压力。

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

关于SQL查询结果排序的疑惑学习SQL的过程中,常常会遇到一些令人困惑的问题。最近,笔者在阅读《MICK-SQL基础�...


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

Atom编辑器mac版下载
最流行的的开源编辑器

SublimeText3汉化版
中文版,非常好用