Was wir bauen werden
Wir werden ein Tool wie make erstellen, mit dem wir Aufgaben mithilfe einer einfachen Yaml-Datei wie dieser ausführen können.
tasks: build: description: "compile the project" command: "go build main.go" dependencies: [test] test: description: "run unit tests" command: "go test -v ./..."
Lasst uns beginnen, zuerst müssen wir die Vorgehensweise skizzieren. Wir haben das Aufgabendateischema bereits definiert. Wir können JSON anstelle von Yaml verwenden, aber für dieses Projekt werden wir YML-Dateien verwenden.
Aus der Datei können wir ersehen, dass wir eine Struktur zum Speichern einer einzelnen Aufgabe und eine Möglichkeit zum Ausführen abhängiger Aufgaben benötigen, bevor wir mit der Hauptaufgabe fortfahren. Beginnen wir mit der Initiierung unseres Projekts. Erstellen Sie einen neuen Ordner und führen Sie Folgendes aus:
go mod init github.com/vishaaxl/mommy
Sie können Ihr Projekt so benennen, wie Sie möchten, ich verwende diesen „Mama“-Namen. Wir müssen auch ein Paket installieren, um mit Yaml-Dateien arbeiten zu können – im Grunde müssen wir sie in ein Kartenobjekt konvertieren. Fahren Sie fort und installieren Sie das folgende Paket.
go get gopkg.in/yaml.v3
Als nächstes erstellen Sie eine neue main.go-Datei und beginnen mit der Definition der „Task“-Struktur.
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. }
Das ist ziemlich selbsterklärend. Dadurch bleibt der Wert jeder einzelnen Aufgabe erhalten. Als nächstes benötigen wir eine weitere Struktur, um die Liste der Aufgaben zu speichern und den Inhalt der .yaml-Datei in dieses neue Objekt zu laden.
// 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 }
Als nächstes müssen wir eine Funktion erstellen, die eine einzelne Aufgabe ausführt. Wir verwenden das Modul os/exec, um die Aufgabe in der Shell auszuführen. In Golang bietet das Paket os/exec eine Möglichkeit, Shell-Befehle und externe Programme auszuführen.
// 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 }
Jetzt haben wir alle Bausteine des Programms und können sie in der Hauptfunktion verwenden, um die Konfigurationsdatei zu laden und mit der Automatisierung zu beginnen. Wir werden das Flag-Paket verwenden, um die Befehlszeilen-Flags zu lesen.
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 } }
Lass uns das Ganze testen, eine neue Mommy.yaml erstellen und den Yaml-Code von Anfang an darin einfügen. Wir werden unseren Task Runner verwenden, um Binärdateien für unser Projekt zu erstellen. Führen Sie aus:
go run main.go -task build
Wenn alles gut geht, sehen Sie eine neue .exe-Datei im Stammverzeichnis des Ordners. Großartig, wir haben jetzt einen funktionierenden Task Runner. Wir können den Speicherort dieser .exe-Datei in den Umgebungsvariablen unseres Systems hinzufügen und diese von überall aus verwenden, indem wir Folgendes verwenden:
mommy -task build
Vollständiger Code
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 } }
Das obige ist der detaillierte Inhalt vonGo-Projekt für Anfänger – Erstellen Sie einen Task Runner in Go. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

TensureinitFunctionsAreefectivenandMainableable: 1) minimiertsideffectsByReturningValuesinsteadofmodifyingglobalState, 2) safidEmpotencytohandlemultiplecallsSafely und 3) BreakdowncomplexinitialisierungIntosmaller, focusedFunctionStoenhEmodulus und maller, undmaller und stunschstörungen und störungen und störungen und störungen und störungen und störungen und störungen und störungen und störungen und störungen und störungen sind, diestöpfenhöreskräkuliskenntn und malker, und maller, und maller, focusedFocusedFunctionStoenhEmodulus und m

GoisidealforBeginersandSuitableforCloudandNetWorkServicesDuetoitsSimplicity, Effizienz und Konsumfeaturen.1) InstallgoFromTheofficialwebSiteAnDverifyWith'goversion'.2) CreateAneDrunyourFirstProgramwith'gorunhello.go.go.go.

Entwickler sollten den folgenden Best Practices folgen: 1. verwalten Goroutinen sorgfältig, um Ressourcenleckage zu verhindern; 2. Verwenden Sie Kanäle zur Synchronisation, aber vermeiden Sie Überbeanspruchung; 3.. Ausdrücklich Fehler in gleichzeitigen Programmen bewältigen; 4. Verstehen Sie GomaxProcs, um die Leistung zu optimieren. Diese Praktiken sind für eine effiziente und robuste Softwareentwicklung von entscheidender Bedeutung, da sie eine effektive Verwaltung von Ressourcen, eine ordnungsgemäße Synchronisierungsimplementierung, die ordnungsgemäße Fehlerbehandlung und die Leistungsoptimierung gewährleisten, wodurch die Software -Effizienz und die Wartbarkeit verbessert werden.

GoexcelsinProductionDuetoitoSperformanceAndSimplicity, ButrequirescarefulmanagementofScalability, Fehlerhandling, Andresources.1) DockerusesgOforeEfficienceContainermanagement -Throughgoroutines.2) Uberscalesmicroserviceswithgo, FacingChallengeengeseragemaMeManageme

Wir müssen den Fehlertyp anpassen, da die Standardfehlerschnittstelle begrenzte Informationen liefert und benutzerdefinierte Typen mehr Kontext und strukturierte Informationen hinzufügen können. 1) Benutzerdefinierte Fehlertypen können Fehlercodes, Positionen, Kontextdaten usw. enthalten, 2) Verbesserung der Debugging -Effizienz und der Benutzererfahrung, 3), aber der Komplexität und Wartungskosten sollte die Aufmerksamkeit geschenkt werden.

GoisidealforbuildingsCalablesSystemsDuetoitsSimplicity, Effizienz und verblüfftem Inconcurrencysupport.1) Go'ScleanSyNtaxandminimalisticDeInenHanceProductivity und ReduzienEirrors.2) ItsgoroutinesandchannelsableCrentCrent-Programme, Distrioutines und ChannelenableCrent-Programme, DistributingworkloNecrent-Programme,

Initunctionsingorunautomatischbeforemain () und sarEsfulForsSetingupenvironmentsandinitializingVariables

GoinitializespackagesintheordertheyareImported, SheexecuteStfunctionSwitHinapackageInredeDinitionorder und FileNamesDeterminetheorderacrossmultipleFiles


Heiße KI -Werkzeuge

Undresser.AI Undress
KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover
Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool
Ausziehbilder kostenlos

Clothoff.io
KI-Kleiderentferner

Video Face Swap
Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

Heiße Werkzeuge

mPDF
mPDF ist eine PHP-Bibliothek, die PDF-Dateien aus UTF-8-codiertem HTML generieren kann. Der ursprüngliche Autor, Ian Back, hat mPDF geschrieben, um PDF-Dateien „on the fly“ von seiner Website auszugeben und verschiedene Sprachen zu verarbeiten. Es ist langsamer und erzeugt bei der Verwendung von Unicode-Schriftarten größere Dateien als Originalskripte wie HTML2FPDF, unterstützt aber CSS-Stile usw. und verfügt über viele Verbesserungen. Unterstützt fast alle Sprachen, einschließlich RTL (Arabisch und Hebräisch) und CJK (Chinesisch, Japanisch und Koreanisch). Unterstützt verschachtelte Elemente auf Blockebene (wie P, DIV),

SecLists
SecLists ist der ultimative Begleiter für Sicherheitstester. Dabei handelt es sich um eine Sammlung verschiedener Arten von Listen, die häufig bei Sicherheitsbewertungen verwendet werden, an einem Ort. SecLists trägt dazu bei, Sicherheitstests effizienter und produktiver zu gestalten, indem es bequem alle Listen bereitstellt, die ein Sicherheitstester benötigen könnte. Zu den Listentypen gehören Benutzernamen, Passwörter, URLs, Fuzzing-Payloads, Muster für vertrauliche Daten, Web-Shells und mehr. Der Tester kann dieses Repository einfach auf einen neuen Testcomputer übertragen und hat dann Zugriff auf alle Arten von Listen, die er benötigt.

VSCode Windows 64-Bit-Download
Ein kostenloser und leistungsstarker IDE-Editor von Microsoft

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

WebStorm-Mac-Version
Nützliche JavaScript-Entwicklungstools
