고라벨 소개
Goravel은 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 개발자는 당황하지 않을 것입니다.
모델, 마이그레이션 및 컨트롤러
모델, 마이그레이션, 컨트롤러를 생성하려면 Laravel에서와 마찬가지로 artisan 명령을 사용할 수 있습니다.
// 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
이제 데이터베이스/마이그레이션 폴더를 확인하면 up 및 down 파일이 생성된 것을 볼 수 있습니다. up 마이그레이션 파일을 열고 아래 코드를 내부에 붙여넣으세요.
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을 사용할 것입니다. 여러 데이터베이스 드라이버가 함께 제공된다는 점에 유의하는 것이 중요합니다. .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
이렇게 하면 DB의 카테고리 테이블이 자동으로 마이그레이션됩니다.
이제 이전에 실행 중이던 서버를 중지하고 다시 시작해야 합니다.
이제 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 작업(GO용 Laravel)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

C는 하드웨어 리소스 및 고성능 최적화가 직접 제어되는 시나리오에 더 적합하지만 Golang은 빠른 개발 및 높은 동시성 처리가 필요한 시나리오에 더 적합합니다. 1.C의 장점은 게임 개발과 같은 고성능 요구에 적합한 하드웨어 특성 및 높은 최적화 기능에 가깝습니다. 2. Golang의 장점은 간결한 구문 및 자연 동시성 지원에 있으며, 이는 동시성 서비스 개발에 적합합니다.

Golang은 실제 응용 분야에서 탁월하며 단순성, 효율성 및 동시성으로 유명합니다. 1) 동시 프로그래밍은 Goroutines 및 채널을 통해 구현됩니다. 2) Flexible Code는 인터페이스 및 다형성을 사용하여 작성됩니다. 3) NET/HTTP 패키지로 네트워크 프로그래밍 단순화, 4) 효율적인 동시 크롤러 구축, 5) 도구 및 모범 사례를 통해 디버깅 및 최적화.

GO의 핵심 기능에는 쓰레기 수집, 정적 연결 및 동시성 지원이 포함됩니다. 1. Go Language의 동시성 모델은 고루틴 및 채널을 통한 효율적인 동시 프로그래밍을 실현합니다. 2. 인터페이스 및 다형성은 인터페이스 방법을 통해 구현되므로 서로 다른 유형을 통일 된 방식으로 처리 할 수 있습니다. 3. 기본 사용법은 기능 정의 및 호출의 효율성을 보여줍니다. 4. 고급 사용에서 슬라이스는 동적 크기 조정의 강력한 기능을 제공합니다. 5. 레이스 조건과 같은 일반적인 오류는 Getest-race를 통해 감지 및 해결할 수 있습니다. 6. 성능 최적화는 sync.pool을 통해 개체를 재사용하여 쓰레기 수집 압력을 줄입니다.

Go Language는 효율적이고 확장 가능한 시스템을 구축하는 데 잘 작동합니다. 장점은 다음과 같습니다. 1. 고성능 : 기계 코드로 컴파일, 빠른 달리기 속도; 2. 동시 프로그래밍 : 고어 라틴 및 채널을 통한 멀티 태스킹 단순화; 3. 단순성 : 간결한 구문, 학습 및 유지 보수 비용 절감; 4. 크로스 플랫폼 : 크로스 플랫폼 컴파일, 쉬운 배포를 지원합니다.

SQL 쿼리 결과의 정렬에 대해 혼란스러워합니다. SQL을 학습하는 과정에서 종종 혼란스러운 문제가 발생합니다. 최근 저자는 "Mick-SQL 기본 사항"을 읽고 있습니다.

기술 스택 컨버전스와 기술 선택의 관계, 소프트웨어 개발에서 기술 스택의 선택 및 관리는 매우 중요한 문제입니다. 최근에 일부 독자들은 ...

골란 ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Dreamweaver Mac版
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.
