Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Golang] Create Your Own CLI — With Golang

Posted on December 21, 2022January 7, 2024 By nim No Comments on [Golang] Create Your Own CLI — With Golang

Bạn muốn viết 1 tool command như bạn chỉ biết golang.
Ahihi quá easy

Contents

Toggle
  • Look into example
  • Provide a CLI tool for yourself.

Look into example

https://github.com/urfave/cli/blob/main/docs/v2/examples/greet.md

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/urfave/cli/v2"
)

func main() {
	app := &cli.App{
		Name:  "greet",
		Usage: "fight the loneliness!",
		Action: func(*cli.Context) error {
			fmt.Println("Hello friend!")
			return nil
		},
	}

	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}

trong phần import github.com/urfave/cli/v2 thì the urfave/cli package to create a command-line application.

Tiếp đến là phần khai báo các thông tin của CLI thông qua &cli.App:

  • Name: The name of the application is set to “greet”.
  • Usage: A short description of the application is provided: “fight the loneliness!”.
  • Action: Defines the action to be performed when this app is executed. In this case, it’s an anonymous function that prints “Hello friend!” to the console. The function returns nil to indicate that it executed successfully.

Tiếp đến là phần thực thi application:
app.Run(os.Args)

  • app: This is an instance of cli.App, which represents the command-line application itself. It contains all the metadata (like name and usage) and configurations (like flags, commands, and actions) that define how the app behaves.
  • .Run(): This is a method of the cli.App struct. It’s responsible for parsing the command-line arguments, handling any specified commands, and invoking the appropriate actions based on the user’s input.
  • os.Args: This is a slice of strings provided by the Go standard library’s os package. It contains all the command-line arguments passed to the program when it’s executed. The first element (os.Args[0]) is always the path to the executed program, and the rest are the arguments and flags passed by the user.

Và đây là thành quả khi bạn go build -o greet và sau đó bạn run file greet help

$ greet help
NAME:
    greet - fight the loneliness!

USAGE:
    greet [global options] command [command options] [arguments...]

COMMANDS:
    help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS
    --help, -h  show help (default: false)

Provide a CLI tool for yourself.

Để hiểu được lý do mình muốn viết cli.
Ban đầu bạn sẽ cần thực thi một công việc gì đó. mình viết bash script. sau đó thì các hàm này gọi hàm kia.
Bash script phức tạp và rối rắm.

It’s high time I needed to code the cli tool.

Bạn cần divide (chia) into each part.
https://github.com/mrnim94/learn_cli/blob/master/main.go

package main

import (
	"github.com/urfave/cli/v2"
	"learn_cli/learn_command"
	"log"
	"os"
)

func main() {
	app := &cli.App{
		Name:  "greeter",
		Usage: "A simple CLI application",
		Commands: []*cli.Command{
			learn_command.GreetCommand(),
			learn_command.CreatePostCommand(),
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}

Bạn sẽ thấy main function will call đến 2 command:
learn_command.GreetCommand() và learn_command.CreatePostCommand()

Việc divide functions hoặc files rất là quan trong nếu tool của chúng ta ngày càng lớn.
Nếu tát cả viết hết trên 1 file thì khách gì viết script.

Tiếp tục tìm hiểu chi tiết các commands:

package learn_command

import (
	"github.com/urfave/cli/v2"
	"learn_cli/learn_action"
)

func GreetCommand() *cli.Command {
	return &cli.Command{
		Name:    "greet",
		Aliases: []string{"g"},
		Usage:   "greets a user",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "name",
				Value: "",
				Usage: "the name of the person to greet",
			},
			&cli.IntFlag{
				Name:  "age",
				Value: 0,
				Usage: "the age of the person",
			},
		},
		Action: learn_action.GreetAction,
	}
}

Bạn có thể thiểu đơn giản như thế này:
Mình tạo file learn_cli.exe (vì mình chạy trên windows)
Mình mong muốn command sẽ là learn_cli.exe greet –name nim –age 30
thì bạn sẽ triển khai funtion như trên.

Tiếp đến nó sẽ gọi đến action là learn_action.GreetAction

Vậy trong file command có gì?

package learn_action

import (
	"fmt"
	"github.com/urfave/cli/v2"
)

func GreetAction(c *cli.Context) error {
	name := c.String("name")
	if name == "" {
		name = "World" // Default value if no name is provided
	}
	age := c.Int("age")

	greeting := fmt.Sprintf("Hello, %s!", name)
	if age > 0 {
		greeting += fmt.Sprintf(" You are %d years old.", age)
	}

	fmt.Println(greeting)
	return nil
}

Nó sẽ ghi nhận các flags mà bạn truyền vào thông qua command và thực hiện sử lý ở đây.

Ví dụ bạn truyền vào là xxxx –name nim.
thì chúng ta có 1 logic để kiêm tra điều này:

        name := c.String("name")
	if name == "" {
		name = "World" // Default value if no name is provided
	}
	age := c.Int("age")

Ngoài ra nếu bạn muốn command là

learn_cli.exe post create –title golang –content ahihi
thì bạn có thể tìm hiểu 2 files:
https://github.com/mrnim94/learn_cli/blob/master/learn_command/post.go

Golang

Post navigation

Previous Post: Conventional Commits
Next Post: [EKS] the exciting and helpful things about EKS

More Related Articles

[Golang] Error obtaining VCS status: exit status 128 Golang
[Golang] Thiết kế model trong golang và echo framework. Golang
Hướng Dẫn Nhúng Tệp Tĩnh Vào Go Sử Dụng go:embed Golang
[Golang] Define mapping when creating an index on Elasticsearch by Golang. ELK
[Golang] In-Memory Cache or Local Cache with Golang. Golang
[Golang] Convert between Json and Struct in Golang Golang

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [AWS/EKS] Cache Docker image to accelerate EKS container deployment. July 10, 2025
  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.