Goravel을 사용한 CRUD 작업(GO용 Laravel)

Linda Hamilton
풀어 주다: 2024-10-08 06:14:01
원래의
966명이 탐색했습니다.

CRUD Operations with Goravel (Laravel for GO)

고라벨 소개

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!