찾다
백엔드 개발Golang초보자 Go 프로젝트 - Go에서 작업 실행기 만들기

Beginner Go Project - Create a Task Runner in Go

우리가 만들려는 것

우리는 이와 같은 간단한 yaml 파일을 사용하여 작업 실행을 사용할 수 있는 make와 같은 도구를 만들 것입니다.

tasks:
    build:
        description:  "compile the project"
        command:  "go build main.go"
        dependencies:  [test]
    test:
        description:  "run unit tests"
        command:  "go test -v ./..."

시작하겠습니다. 먼저 조치 과정을 개략적으로 설명해야 합니다. 우리는 이미 작업 파일 스키마를 정의했습니다. yaml 대신 json을 사용할 수 있지만 이 프로젝트에서는 yml 파일을 사용하겠습니다.

파일에서 단일 작업을 저장하기 위한 구조체와 기본 작업을 진행하기 전에 종속 작업을 실행하는 방법이 필요하다는 것을 알 수 있습니다. 프로젝트를 시작하는 것부터 시작해 보겠습니다. 새 폴더를 만들고 다음을 실행하세요.

go mod init github.com/vishaaxl/mommy

프로젝트 이름은 원하는 대로 지정할 수 있습니다. 저는 '엄마' 이름을 사용하겠습니다. 또한 yaml 파일을 사용하려면 일부 패키지를 설치해야 합니다. 기본적으로 해당 파일을 지도 객체로 변환합니다. 다음 패키지를 설치해 보세요.

go get gopkg.in/yaml.v3

다음으로 새 main.go 파일을 만들고 'Task' 구조체 정의부터 시작합니다.

package main

import (
    "gopkg.in/yaml.v3"
)
// Task defines the structure of a task in the configuration file.
// Each task has a description, a command to run, and a list of dependencies
// (other tasks that need to be completed before this task).
type Task struct {
    Description  string   `yaml:"description"`  // A brief description of the task.
    Command      string   `yaml:"command"`      // The shell command to execute for the task.
    Dependencies []string `yaml:"dependencies"` // List of tasks that need to be completed before this task.
}

이것은 꽤 자명합니다. 이는 각 개별 작업의 가치를 유지합니다. 다음으로 작업 목록을 저장하고 .yaml 파일의 내용을 이 새 개체에 로드하려면 구조체가 하나 더 필요합니다.

// Config represents the entire configuration file,
// which contains a map of tasks by name.
type Config struct {
    Tasks map[string]Task `yaml:"tasks"` // A map of task names to task details.
}

// loadConfig reads and parses the configuration file (e.g., Makefile.yaml),
// and returns a Config struct containing the tasks and their details.
func loadConfig(filename string) (Config, error) {
    // Read the content of the config file.
    data, err := os.ReadFile(filename)
    if err != nil {
        return Config{}, err
    }

    // Unmarshal the YAML data into a Config struct.
    var config Config
    err = yaml.Unmarshal(data, &config)
    if err != nil {
        return Config{}, err
    }

    return config, nil
}

다음으로 단일 작업을 실행하는 함수를 만들어야 합니다. 우리는 쉘에서 작업을 실행하기 위해 os/exec 모듈을 사용할 것입니다. Golang에서 os/exec 패키지는 셸 명령과 외부 프로그램을 실행하는 방법을 제공합니다.

// executeTask recursively executes the specified task and its dependencies.
// It first ensures that all dependencies are executed before running the current task's command.
func executeTask(taskName string, tasks map[string]Task, executed map[string]bool) error {
    // If the task has already been executed, skip it.
    if executed[taskName] {
        return nil
    }

    // Get the task details from the tasks map.
    task, exists := tasks[taskName]
    if !exists {
        return fmt.Errorf("task %s not found", taskName)
    }

    // First, execute all the dependencies of this task.
    for _, dep := range task.Dependencies {
        // Recursively execute each dependency.
        if err := executeTask(dep, tasks, executed); err != nil {
            return err
        }
    }

    // Now that dependencies are executed, run the task's command.
    fmt.Printf("Running task: %s\n", taskName)
    fmt.Printf("Command: %s\n", task.Command)

    // Execute the task's command using the shell (sh -c allows for complex shell commands).
    cmd := exec.Command("sh", "-c", task.Command)
    cmd.Stdout = os.Stdout // Direct standard output to the terminal.
    cmd.Stderr = os.Stderr // Direct error output to the terminal.

    // Run the command and check for any errors.
    if err := cmd.Run(); err != nil {
        return fmt.Errorf("failed to execute command %s: %v", task.Command, err)
    }

    // Mark the task as executed.
    executed[taskName] = true
    return nil
}

이제 구성 파일을 로드하고 자동화를 시작하기 위해 기본 기능에서 사용할 수 있는 프로그램의 모든 구성 요소가 있습니다. 우리는 명령줄 플래그를 읽기 위해 플래그 패키지를 사용할 것입니다.

func main() {
    // Define command-line flags
    configFile := flag.String("f", "Mommy.yaml", "Path to the configuration file") // Path to the config file (defaults to Makefile.yaml)
    taskName := flag.String("task", "", "Task to execute")                             // The task to execute (required flag)

    // Parse the flags
    flag.Parse()

    // Check if the task flag is provided
    if *taskName == "" {
        fmt.Println("Error: Please specify a task using -task flag.")
        os.Exit(1) // Exit if no task is provided
    }

    // Load the configuration file
    config, err := loadConfig(*configFile)
    if err != nil {
        fmt.Printf("Failed to load config: %v\n", err)
        os.Exit(1) // Exit if the configuration file can't be loaded
    }

    // Map to track which tasks have been executed already (avoiding re-execution).
    executed := make(map[string]bool)

    // Start executing the specified task (with dependencies)
    if err := executeTask(*taskName, config.Tasks, executed); err != nil {
        fmt.Printf("Error executing task: %v\n", err)
        os.Exit(1) // Exit if task execution fails
    }
}

전체를 테스트하고 새 Mommy.yaml을 생성한 후 처음부터 yaml 코드를 붙여넣어 보겠습니다. 우리는 작업 실행기를 사용하여 프로젝트에 대한 바이너리를 만들 것입니다. 실행:

go run main.go -task build

모든 문제가 해결되면 폴더 루트에 새 .exe 파일이 표시됩니다. 좋습니다. 이제 작업 중인 작업 실행기가 생겼습니다. 시스템의 환경 변수에 이 .exe 파일의 위치를 ​​추가하고 다음을 사용하여 어디에서나 사용할 수 있습니다.

 mommy -task build

완전한 코드

package main

import (
    "flag"
    "fmt"
    "os"
    "os/exec"
    "gopkg.in/yaml.v3"
)

// Task defines the structure of a task in the configuration file.
// Each task has a description, a command to run, and a list of dependencies
// (other tasks that need to be completed before this task).
type Task struct {
    Description  string   `yaml:"description"`  // A brief description of the task.
    Command      string   `yaml:"command"`      // The shell command to execute for the task.
    Dependencies []string `yaml:"dependencies"` // List of tasks that need to be completed before this task.
}

// Config represents the entire configuration file,
// which contains a map of tasks by name.
type Config struct {
    Tasks map[string]Task `yaml:"tasks"` // A map of task names to task details.
}

// loadConfig reads and parses the configuration file (e.g., Makefile.yaml),
// and returns a Config struct containing the tasks and their details.
func loadConfig(filename string) (Config, error) {
    // Read the content of the config file.
    data, err := os.ReadFile(filename)
    if err != nil {
        return Config{}, err
    }

    // Unmarshal the YAML data into a Config struct.
    var config Config
    err = yaml.Unmarshal(data, &config)
    if err != nil {
        return Config{}, err
    }

    return config, nil
}

// executeTask recursively executes the specified task and its dependencies.
// It first ensures that all dependencies are executed before running the current task's command.
func executeTask(taskName string, tasks map[string]Task, executed map[string]bool) error {
    // If the task has already been executed, skip it.
    if executed[taskName] {
        return nil
    }

    // Get the task details from the tasks map.
    task, exists := tasks[taskName]
    if !exists {
        return fmt.Errorf("task %s not found", taskName)
    }

    // First, execute all the dependencies of this task.
    for _, dep := range task.Dependencies {
        // Recursively execute each dependency.
        if err := executeTask(dep, tasks, executed); err != nil {
            return err
        }
    }

    // Now that dependencies are executed, run the task's command.
    fmt.Printf("Running task: %s\n", taskName)
    fmt.Printf("Command: %s\n", task.Command)

    // Execute the task's command using the shell (sh -c allows for complex shell commands).
    cmd := exec.Command("sh", "-c", task.Command)
    cmd.Stdout = os.Stdout // Direct standard output to the terminal.
    cmd.Stderr = os.Stderr // Direct error output to the terminal.

    // Run the command and check for any errors.
    if err := cmd.Run(); err != nil {
        return fmt.Errorf("failed to execute command %s: %v", task.Command, err)
    }

    // Mark the task as executed.
    executed[taskName] = true
    return nil
}

func main() {
    // Define command-line flags
    configFile := flag.String("f", "Makefile.yaml", "Path to the configuration file") // Path to the config file (defaults to Makefile.yaml)
    taskName := flag.String("task", "", "Task to execute")                             // The task to execute (required flag)

    // Parse the flags
    flag.Parse()

    // Check if the task flag is provided
    if *taskName == "" {
        fmt.Println("Error: Please specify a task using -task flag.")
        os.Exit(1) // Exit if no task is provided
    }

    // Load the configuration file
    config, err := loadConfig(*configFile)
    if err != nil {
        fmt.Printf("Failed to load config: %v\n", err)
        os.Exit(1) // Exit if the configuration file can't be loaded
    }

    // Map to track which tasks have been executed already (avoiding re-execution).
    executed := make(map[string]bool)

    // Start executing the specified task (with dependencies)
    if err := executeTask(*taskName, config.Tasks, executed); err != nil {
        fmt.Printf("Error executing task: %v\n", err)
        os.Exit(1) // Exit if task execution fails
    }
}

위 내용은 초보자 Go 프로젝트 - Go에서 작업 실행기 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Debian에서 Liboffice의 보안 설정을 수행하는 방법Debian에서 Liboffice의 보안 설정을 수행하는 방법May 16, 2025 pm 01:24 PM

Debian 시스템의 전반적인 보안을 보장하는 것은 Liboffice와 같은 응용 프로그램의 실행 환경을 보호하는 데 중요합니다. 시스템 보안 개선을위한 몇 가지 일반적인 권장 사항은 다음과 같습니다. 시스템 업데이트는 시스템을 정기적으로 알려진 보안 취약점으로 업데이트합니다. Debian12.10은 일부 중요한 소프트웨어 패키지를 포함하여 많은 보안 취약점을 수정 한 보안 업데이트를 공개했습니다. 사용자 권한 관리는 잠재적 인 보안 위험을 줄이기 위해 일상 운영에 루트 사용자를 사용하지 않습니다. 일반 사용자를 생성하고 Sudo 그룹에 가입하여 시스템에 대한 직접 액세스를 제한하는 것이 좋습니다. SSH 서비스 보안 구성은 SSH 키 쌍을 사용하여 루트 원격 로그인을 인증하고 비활성화하며 빈 비밀번호로 로그인을 제한합니다. 이러한 조치는 SSH 서비스의 보안을 향상시키고 예방할 수 있습니다.

데비안에서 녹 컴파일 옵션을 구성하는 방법데비안에서 녹 컴파일 옵션을 구성하는 방법May 16, 2025 pm 01:21 PM

데비안 시스템에서 녹 컴파일 옵션 조정은 다양한 방법을 통해 달성 할 수 있습니다. 다음은 몇 가지 방법에 대한 자세한 설명입니다. Rustup 도구를 사용하여 Rustup을 구성하고 설치하십시오. Rustup을 아직 설치하지 않은 경우 다음 명령을 사용하여 설치할 수 있습니다. Curl-- Proto '= https'-TLSV1.2-SSFHTTPS : ///sh.rustup.rs | Sh Prompts를 따라 설치 프로세스를 완료하십시오. 컴파일 설정 옵션 : Rustup을 사용하여 다양한 도구 체인 및 대상의 컴파일 옵션을 구성 할 수 있습니다. RustupOverride 명령을 사용하여 특정 프로젝트에 대한 컴파일 옵션을 설정할 수 있습니다. 예를 들어, 프로젝트에 대한 특정 Rust 버전을 설정하려면

데비안에서 Kubernetes 노드를 관리하는 방법데비안에서 Kubernetes 노드를 관리하는 방법May 16, 2025 pm 01:18 PM

데비안 시스템에서 Kubernetes (K8S) 노드 관리는 일반적으로 다음과 같은 주요 단계가 필요합니다. 1. Kubernetes 구성 요소 설치 및 구성 : 모든 노드 (마스터 노드 및 작업자 노드 포함)는 데비안 운영 체제가 설치되어 있으며 CPU, 메모리 및 디스크 공간과 같은 Kubernetes 클러스터를 설치하기위한 기본 요구 사항을 충족합니다. 스왑 파티션 비활성화 : Kubelet이 원활하게 작동 할 수 있도록 스왑 파티션을 비활성화하는 것이 좋습니다. 방화벽 규칙 설정 : Kubelet, Kube-Apiserver, Kube-Scheduler에서 사용하는 포트와 같은 필요한 포트를 허용합니다. 설치 컨테이너 설치

데비안에 대한 골랑의 보안 설정데비안에 대한 골랑의 보안 설정May 16, 2025 pm 01:15 PM

데비안에 골랑 환경을 설정할 때는 시스템 보안을 보장하는 것이 중요합니다. 다음은 안전한 Golang 개발 환경을 구축하는 데 도움이되는 몇 가지 주요 보안 설정 단계 및 제안 사항입니다. 보안 설정 단계 시스템 업데이트 : Golang을 설치하기 전에 시스템이 최신 상태인지 확인하십시오. 다음 명령으로 시스템 패키지 목록 및 설치된 패키지를 업데이트하십시오. sudoaptupdatesudoaptupgrade-y 방화벽 구성 : 방화벽 (예 : iptables)을 설치하고 구성하여 시스템 액세스를 제한하십시오. 필요한 포트 (예 : HTTP, HTTP 및 SSH) 만 허용됩니다. sudoaptininstalliptablessud

데비안에서 Kubernetes 배포 성능을 최적화하는 방법데비안에서 Kubernetes 배포 성능을 최적화하는 방법May 16, 2025 pm 01:12 PM

데비안에서 Kubernetes 클러스터 성능을 최적화하고 배포하는 것은 여러 측면을 포함하는 복잡한 작업입니다. 주요 최적화 전략 및 제안은 다음과 같습니다. 하드웨어 리소스 최적화 CPU : 충분한 CPU 리소스가 Kubernetes 노드 및 포드에 할당되도록하십시오. 메모리 : 특히 메모리 집약적 인 응용 프로그램의 경우 노드의 메모리 용량을 증가시킵니다. 저장소 : 고성능 SSD 스토리지를 사용하고 NFS와 같은 네트워크 파일 시스템 (예 : 대기 시간을 소개 할 수있는 네트워크 파일 시스템)을 사용하지 마십시오. 커널 매개 변수 최적화 편집 /etc/sysctl.conf 파일, 다음 매개 변수를 추가하거나 수정하십시오 : net.core.somaxconn : 65535net.ipv4.tcp_max_syn

Python 스크립트로 Debian에서 작업을 예약하는 방법Python 스크립트로 Debian에서 작업을 예약하는 방법May 16, 2025 pm 01:09 PM

데비안 시스템에서는 CRON을 사용하여 시간이 지정된 작업을 정리하고 파이썬 스크립트의 자동 실행을 인식 할 수 있습니다. 먼저 터미널을 시작하십시오. 다음 명령을 입력하여 현재 사용자의 Crontab 파일 편집 : Crontab-e 루트 권한이있는 다른 사용자의 Crontab 파일을 편집 해야하는 경우 : 사용자 이름을 편집하려는 사용자 이름으로 대체하려면 Sudocrontab-Uusername-e를 사용하십시오. Crontab 파일에서 다음과 같이 형식으로 시간이 지정된 작업을 추가 할 수 있습니다. *****/path/to/your/python-script.py이 5 개의 별표는 분 (0-59)과 작은 것을 나타냅니다.

데비안에서 Golang 네트워크 매개 변수를 구성하는 방법데비안에서 Golang 네트워크 매개 변수를 구성하는 방법May 16, 2025 pm 01:06 PM

데비안 시스템에서 Golang의 네트워크 매개 변수를 조정하는 것은 여러 가지 방법으로 달성 할 수 있습니다. 다음은 몇 가지 실현 가능한 방법입니다. 방법 1 : 환경 변수를 설정하여 일시적으로 환경 변수를 설정하십시오. 터미널에 다음 명령을 입력하여 일시적으로 환경 변수를 설정하면이 설정은 현재 세션에서만 유효합니다. ExportGodeBug = "gctrace = 1netdns = go"여기서 gctrace = 1은 쓰레기 수집 추적을 활성화하고 netdns = Go는 시스템 기본 대신 자체 DNS 리졸버를 사용하게됩니다. 환경 변수를 영구적으로 설정 : ~/.bashrc 또는 ~/.profile과 같은 쉘 구성 파일에 위 명령을 추가하십시오.

Debian의 Liboffice를위한 바로 가기 키는 무엇입니까?Debian의 Liboffice를위한 바로 가기 키는 무엇입니까?May 16, 2025 pm 01:03 PM

데비안 시스템에서 Liboffice를 사용자 정의하기위한 바로 가기 키는 시스템 설정을 통해 조정할 수 있습니다. 다음은 Liboffice 바로 가기 키를 설정하는 데 일반적으로 사용되는 몇 가지 단계와 방법입니다. 기본 단계 Liboffice 바로 가기 키 열기 시스템 설정 : 데비안 시스템에서 왼쪽 상단 모서리의 메뉴 (일반적으로 기어 아이콘)를 클릭하고 "시스템 설정"을 선택하십시오. 장치 선택 : 시스템 설정 창에서 "장치"를 선택하십시오. 키보드 선택 : 장치 설정 페이지에서 키보드를 선택하십시오. 해당 도구에 대한 명령을 찾으십시오. 키보드 설정 페이지에서 하단으로 스크롤하여 "바로 가기 키"옵션을 확인하십시오. 그것을 클릭하면 창이 팝업으로 연결됩니다. 팝업 창에서 해당 Liboffice 작업자를 찾으십시오

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.