搜索
首页后端开发Golang初学者 Go 项目 - 在 Go 中创建任务运行程序

Beginner Go Project - Create a Task Runner in Go

我们要建造什么

我们将制作一个像 make 这样的工具,我们可以使用像这样的简单 yaml 文件来运行任务。

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

让我们开始吧,首先我们需要概述行动过程。我们已经定义了任务文件架构。我们可以使用 json 代替 yaml,但为了这个项目,我们将使用 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 模块在 shell 中运行任务。 在 Golang 中,os/exec 包提供了一种执行 shell 命令和外部程序的方法。

// 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
}

现在我们拥有了程序的所有构建块,我们可以在主函数中使用它们来加载配置文件并开始自动化。我们将使用 flag 包来读取命令行标志。

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
Golang在Debian上的安全设置Golang在Debian上的安全设置May 16, 2025 pm 01:15 PM

在Debian上设置Golang环境时,确保系统安全是至关重要的。以下是一些关键的安全设置步骤和建议,帮助您构建一个安全的Golang开发环境:安全设置步骤系统更新:在安装Golang之前,确保系统是最新的。使用以下命令更新系统软件包列表和已安装的软件包:sudoaptupdatesudoaptupgrade-y防火墙配置:安装并配置防火墙(如iptables)以限制对系统的访问。仅允许必要的端口(如HTTP、HTTPS和SSH)连接。sudoaptinstalliptablessud

Debian上Kubernetes部署的性能如何调优Debian上Kubernetes部署的性能如何调优May 16, 2025 pm 01:12 PM

在Debian上优化和部署Kubernetes集群的性能是一个涉及多个方面的复杂任务。以下是一些关键的优化策略和建议:硬件资源优化CPU:确保为Kubernetes节点和Pod分配足够的CPU资源。内存:增加节点的内存容量,特别是对于内存密集型应用。存储:使用高性能的SSD存储,避免使用网络文件系统(如NFS),因为它们可能会引入延迟。内核参数优化编辑/etc/sysctl.conf文件,添加或修改以下参数:net.core.somaxconn:65535net.ipv4.tcp_max_syn

Python脚本在Debian如何定时任务Python脚本在Debian如何定时任务May 16, 2025 pm 01:09 PM

在Debian系统中,你可以利用cron来安排定时任务,实现Python脚本的自动化执行。首先,启动终端。通过输入以下命令,编辑当前用户的crontab文件:crontab-e如果需要以root权限编辑其他用户的crontab文件,请使用:sudocrontab-uusername-e将username替换为你要编辑的用户名。在crontab文件中,你可以添加定时任务,格式如下:*****/path/to/your/python-script.py这五个星号分别代表分钟(0-59)、小

Debian如何配置Golang网络参数Debian如何配置Golang网络参数May 16, 2025 pm 01:06 PM

在Debian系统中调整Golang的网络参数可以通过多种方式实现,以下是几种可行的方法:方法一:通过设置环境变量临时设置环境变量:在终端中输入以下命令可以临时设置环境变量,此设置仅在当前会话有效。exportGODEBUG="gctrace=1netdns=go"其中,gctrace=1会激活垃圾回收跟踪,netdns=go则使Go使用其自身的DNS解析器而非系统默认的。永久设置环境变量:将上述命令添加到你的shell配置文件中,例如~/.bashrc或~/.profile

LibOffice在Debian上的快捷键有哪些LibOffice在Debian上的快捷键有哪些May 16, 2025 pm 01:03 PM

在Debian系统上自定义LibOffice的快捷键可以通过系统设置进行调整。以下是一些常用的步骤和方法来设置LibOffice的快捷键:设置LibOffice快捷键的基本步骤打开系统设置:在Debian系统中,点击左上角的菜单(通常是一个齿轮图标),然后选择“系统设置”。选择设备:在系统设置窗口中,选择“设备”。选择键盘:在设备设置页面中,选择“键盘”。找到对应工具的命令:在键盘设置页面中,向下滚动到最底部可以看到“快捷键”选项,点击它会弹出一个窗口。在弹出的窗口中找到对应LibOffice工

Debian部署Kubernetes有哪些注意事项Debian部署Kubernetes有哪些注意事项May 16, 2025 pm 01:00 PM

在Debian系统上部署Kubernetes(K8s)集群时,需要关注多个关键点,以确保集群的稳定性和安全性。以下是一些主要的注意事项:禁用Swap分区:从Kubernetes1.8版本开始,需要禁用Swap分区。可以使用以下命令临时禁用Swap:sudoswapoff-a若要永久禁用Swap,需编辑/etc/fstab文件,并注释掉包含“swap”的行。设置内核参数:启用IPv4转发:sudotee/etc/sysctl.d/k8s.conf设置网络参数,如net.bridge.brid

Kubernetes部署在Debian上有哪些优势Kubernetes部署在Debian上有哪些优势May 16, 2025 pm 12:57 PM

Kubernetes(简称K8s)在Debian上部署具有以下优势:稳定性:Debian是一个稳定且可靠的操作系统,适合作为Kubernetes的运行环境。许多教程推荐使用Debian12作为底层操作系统进行Kubernetes的部署,这表明Debian提供了可靠的运行环境,能够满足Kubernetes对操作系统的基本要求。安全性:Debian提供了强大的安全特性,如SELinux和AppArmor,可以进一步增强Kubernetes集群的安全性。通过合理的配置和优化措施,可以确保Kuberne

如何在Debian上部署Kubernetes集群如何在Debian上部署Kubernetes集群May 16, 2025 pm 12:54 PM

在Debian系统上部署Kubernetes集群可以通过多种方法实现,以下是利用kubeadm工具在Debian12上设置Kubernetes集群的详细步骤:预备工作确保你的Debian系统已经更新到最新版本。确保你拥有具有管理员权限的sudo用户。确保所有节点之间可以通过稳定网络互相连接。安装步骤设置主机名和更新hosts文件:在每个节点上,使用hostnamectl命令设置主机名,并在/etc/hosts文件中添加节点IP与主机名的对应关系。禁用所有节点的swap分区:为了让kubelet正

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具