検索
ホームページバックエンド開発GolangGo CLI ベースの Todo アプリ

Go CLI based Todo app

Go CLI based Todo app

使用する外部ライブラリをインストールする


github.com/aquasecurity/table
を取得してください

ディレクトリ構造

Go CLI based Todo app

メイン.ゴー

package main

func main() {
    todos := Todos{}

    storage := NewStorage[Todos]("todos.json")
    storage.Load(&todos)

    CmdFlags := NewCmdflags()
    CmdFlags.Execute(&todos)

    storage.Save(todos)
}
  1. 構造名 Todos のスライスを作成しています
  2. 以前に storage.Save で作成した「todo.json」ファイルに、システム内の既存の todo 用の動的メモリをローカルに作成します
  3. そうでない場合は空としてロードされます
  4. ユーザーが提供したコマンド フラグを解析して検証します
  5. 提供されたフラグに基づいて実行します

機能の実装

package main

import (
    "errors"
    "fmt"
    "os"
    "strconv"
    "time"

    "github.com/aquasecurity/table"
)

type Todo struct {
    Title     string
    Completed bool
    CreatedAt time.Time
    // this field here is a pointer reference because it can be null
    CompletedAt *time.Time
}

// a slice(array) of Todo
type Todos []Todo

// Passing Todo slice here as a reference
// declares a parameter named todos that is a pointer to a Todos slice.
// the function receives a copy of the slice under the name todos
func (todos *Todos) add(title string) {
    todo := Todo{
        Title:       title,
        Completed:   false,
        CompletedAt: nil,
        CreatedAt:   time.Now(),
    }
    *todos = append(*todos, todo)

}

func (todos *Todos) validateIndex(index int) error {
    if index = len(*todos) {
        err := errors.New("invalid index")
        fmt.Println(err)
    }
    return nil
}

func (todos *Todos) delete(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    *todos = append(t[:index], t[index+1:]...)

    return nil
}

func (todos *Todos) toggle(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    isCompleted := t[index].Completed

    if !isCompleted {
        completionTime := time.Now()
        t[index].CompletedAt = &completionTime
    }

    t[index].Completed = !isCompleted

    return nil
}

func (todos *Todos) edit(index int, title string) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    t[index].Title = title

    return nil
}

func (todos *Todos) print() {
    table := table.New(os.Stdout)
    table.SetRowLines(false)
    table.SetHeaders("#", "Title", "Status", "Created", "Completed")

    for index, t := range *todos {
        mark := "❌"
        completedAt := ""

        if t.Completed {
            mark = "✅"
            if t.CompletedAt != nil {
                completedAt = t.CompletedAt.Format(time.RFC1123)
            }
        }
        table.AddRow(strconv.Itoa(index), t.Title, mark, t.CreatedAt.Format(time.RFC1123), completedAt)
    }

    table.Render()
}

ストレージの実装

package main

import (
    "encoding/json"
    "os"
)

type Storage[T any] struct {
    FileName string
}

func NewStorage[T any](filename string) *Storage[T] {
    return &Storage[T]{FileName: filename}
}

func (s *Storage[T]) Save(data T) error {
    fileData, err := json.MarshalIndent(data, "", "\t")

    if err != nil {
        return err
    }

    return os.WriteFile(s.FileName, fileData, 0644)

}

func (s *Storage[T]) Load(data *T) error {
    fileData, err := os.ReadFile(s.FileName)

    if err != nil {
        return err
    }

    return json.Unmarshal(fileData, data)
}

コマンドラインフラグの検証と実行

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
    "strings"
)

type CmdFlags struct {
    Help   bool
    Add    string
    Del    int
    Edit   string
    Update int
    List   bool
}

func NewCmdflags() *CmdFlags {
    cf := CmdFlags{}

    flag.BoolVar(&cf.Help, "help", false, "List existing commands")
    flag.StringVar(&cf.Add, "add", "", "Add a new todo specify title")
    flag.StringVar(&cf.Edit, "edit", "", "Edit an existing todo, enter #index and specify a new title. \"id:new title\"")
    flag.IntVar(&cf.Del, "del", -1, "Specify a todo by #index to delete")
    flag.IntVar(&cf.Update, "update", -1, "Specify a todo #index to update")
    flag.BoolVar(&cf.List, "list", false, "List all todos")

    for _, arg := range os.Args[1:] {
        if strings.HasPrefix(arg, "-") && !isValidFlag(arg) {
            fmt.Printf("Unknown flag: %s\n", arg)
            fmt.Println("try --help to know more")

            os.Exit(0)
        }
    }

    flag.Parse()
    return &cf
}

func isValidFlag(flag string) bool {

    validFlags := []string{
        "-help", "--help",
        "-add", "--add",
        "-edit", "--edit",
        "-del", "--del",
        "-update", "--update",
        "-list", "--list",
    }

    if idx := strings.Index(flag, "="); idx != -1 {
        flag = flag[:idx]
    }

    for _, validFlag := range validFlags {
        if flag == validFlag {
            return true
        }
    }

    return false
}

func (cf *CmdFlags) Execute(todos *Todos) {
    switch {
    case cf.List:
        todos.print()

    case cf.Add != "":
        todos.add(cf.Add)

    case cf.Edit != "":
        parts := strings.SplitN(cf.Edit, ":", 2)
        if len(parts) != 2 {
            fmt.Printf("Error, invalid format for edit.\nCorrect Format: \"id:new title\" ")
            os.Exit(1)
        }

        index, err := strconv.Atoi(parts[0])

        if err != nil {
            fmt.Printf("Error, Invalid index for edit")
            os.Exit(1)
        }

        todos.edit(index, parts[1])

    case cf.Update != -1:
        todos.toggle(cf.Update)

    case cf.Del != -1:
        todos.delete(cf.Del)

    case cf.Help:
        fmt.Println("usage:")
        fmt.Println("--help\t\t| List existing commands")
        fmt.Println("--add\t\t| Add new task")
        fmt.Println("--del\t\t| Delete an existing task")
        fmt.Println("--update\t| Check/Uncheck existing task")
        fmt.Println("--edit\t\t| Edit an existing task")
    }
}

Github リポジトリ: CLI Todo アプリ

以上がGo CLI ベースの Todo アプリの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
MicroservicesアーキテクチャにGOを使用することの利点MicroservicesアーキテクチャにGOを使用することの利点Apr 24, 2025 pm 04:29 PM

goisbenefineformicroservicesdueToitssimplicity、and androbustconcurrencysupport.1)go'sdesignemphasisisimplicityandeficiency、ityformicroservices.2)itscurrencymodelusinggoroutinesandchanlowsallowseaseaseadlinging handlingy.3)

Golang vs. Python:長所と短所Golang vs. Python:長所と短所Apr 21, 2025 am 12:17 AM

GolangisidealforBuildingsCalables Systemsduetoitsefficiency andConcurrency、Whilepythonexcelsinquickscriptinganddataanalysisduetoitssimplicityand vastecosystem.golang'ssignencouragesclean、readisinediteNeditinesinedinediseNabletinedinedinedisedisedioncourase

Golang and C:Concurrency vs. Raw SpeedGolang and C:Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golangは並行性がCよりも優れていますが、Cは生の速度ではGolangよりも優れています。 1)Golangは、GoroutineとChannelを通じて効率的な並行性を達成します。これは、多数の同時タスクの処理に適しています。 2)Cコンパイラの最適化と標準ライブラリを介して、極端な最適化を必要とするアプリケーションに適したハードウェアに近い高性能を提供します。

なぜゴランを使うのですか?説明された利点と利点が説明されていますなぜゴランを使うのですか?説明された利点と利点が説明されていますApr 21, 2025 am 12:15 AM

Golangを選択する理由には、1)高い並行性パフォーマンス、2)静的タイプシステム、3)ガベージ収集メカニズム、4)豊富な標準ライブラリとエコシステムは、効率的で信頼できるソフトウェアを開発するための理想的な選択肢となります。

Golang vs. C:パフォーマンスと速度の比較Golang vs. C:パフォーマンスと速度の比較Apr 21, 2025 am 12:13 AM

Golangは迅速な発展と同時シナリオに適しており、Cは極端なパフォーマンスと低レベルの制御が必要なシナリオに適しています。 1)Golangは、ごみ収集と並行機関のメカニズムを通じてパフォーマンスを向上させ、高配列Webサービス開発に適しています。 2)Cは、手動のメモリ管理とコンパイラの最適化を通じて究極のパフォーマンスを実現し、埋め込みシステム開発に適しています。

GolangはCよりも速いですか?制限の調査GolangはCよりも速いですか?制限の調査Apr 20, 2025 am 12:19 AM

Golangは、コンピレーション時間と同時処理においてより良いパフォーマンスを発揮しますが、Cはランニング速度とメモリ管理においてより多くの利点があります。 1.Golangの編集速度は速く、迅速な発展に適しています。 2.Cは速く実行され、パフォーマンスクリティカルなアプリケーションに適しています。 3. Golangは、同時処理においてシンプルで効率的で、同時プログラミングに適しています。 4.Cマニュアルメモリ管理により、パフォーマンスが高くなりますが、開発の複雑さが向上します。

Golang:WebサービスからシステムプログラミングまでGolang:WebサービスからシステムプログラミングまでApr 20, 2025 am 12:18 AM

WebサービスとシステムプログラミングへのGolangのアプリケーションは、主にそのシンプルさ、効率性、並行性に反映されています。 1)Webサービスでは、Golangは、強力なHTTPライブラリと同時処理機能を介して、高性能WebアプリケーションとAPIの作成をサポートしています。 2)システムプログラミングでは、Golangはハードウェアに近い機能とC言語との互換性を使用して、オペレーティングシステムの開発と組み込みシステムに適しています。

Golang vs. C:ベンチマークと現実世界のパフォーマンスGolang vs. C:ベンチマークと現実世界のパフォーマンスApr 20, 2025 am 12:18 AM

GolangとCには、パフォーマンスの比較に独自の利点と欠点があります。1。ゴーランは、高い並行性と迅速な発展に適していますが、ごみ収集はパフォーマンスに影響を与える可能性があります。 2.Cは、パフォーマンスとハードウェア制御を高くしますが、開発の複雑さが高くなります。選択を行うときは、プロジェクトの要件とチームのスキルを包括的な方法で考慮する必要があります。

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 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。