一般的な Golang ライブラリ cobra
golang の次のチュートリアル コラムでは、一般的な golang ライブラリである cobra について紹介します。困っている友人の役に立てば幸いです。
cobra は、コマンド ライン ツールの作成に使用できる Go 言語のライブラリです。通常、git pull 、
docker container start 、
apt install などのコマンドが表示されますが、これらは corba で簡単に実装できます。バイナリ ファイルにコンパイルするのが簡単です。この記事では、単純なコマンド ライン ツールを実装します。
blog というコマンドを設計します。
blog new [post-name] :创建一篇新的blog blog list :列出当前有哪些文章 blog delete [post-name]: 删除某一篇文章 blog edit [post-name]:编辑某一篇文章
- create Module
- cobra のコマンド ラインを使用してコマンド ライン エントリを作成します
- cobra のコマンド ラインを使用してサブコマンドを作成します
- 関数ロジックを作成します
$ go mod init github.com/shalk/blog
go: creating new go.mod: module github.com/shalk/blog
ログイン後にコピー
コマンド ライン エントリの作成コマンド ラインと言えば、さまざまなスタイルのコマンド ラインを解析できる bash の getopt や Java の jcommand を思い浮かべるかもしれませんが、通常はこれらのコマンド ラインが決まった書き方があり、この書き方が覚えられない場合は、テンプレートを探して以下を参考にするのが一般的です。コマンドラインの解析に加えて、cobra はテンプレートを生成できるコマンドラインも提供します。まずこのコマンド ラインをインストールし、ライブラリの依存関係を go.mod に追加します。
$ go mod init github.com/shalk/blog go: creating new go.mod: module github.com/shalk/blog
$ go get -u github.com/spf13/cobra/cobra
$GOPATH\bin ディレクトリにインストールされます。
$ cobra init --pkg-name github.com/shalk/blog -a shalk -l mit Your Cobra applicaton is ready at D:\code\github.com\shalk\blog
./cmd ./cmd/root.go ./go.mod ./go.sum ./LICENSE ./main.go
go build -o blog .
$blog -h A longer description that spans multiple lines and likely contains examples and usage of using your application. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.
go get -u test.com/a/b
- コマンド自体の基本情報を定義する必要があります。 command で表される特定のオブジェクト cobra.Command
- コマンドの一部の機能またはオプションであり、flag で表されます 特定のオブジェクトは、flag.FlagSet
- の最後のパラメータです。 by args, 通常 []string
// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "blog", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your application. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, // Uncomment the following line if your bare application // has an action associated with it: // Run: func(cmd *cobra.Command, args []string) { }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports persistent flags, which, if defined here, // will be global for your application. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.blog.yaml)") // Cobra also supports local flags, which will only run // when this action is called directly. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
D:\code\github.com\shalk\blog>cobra add new
new created at D:\code\github.com\shalk\blog
D:\code\github.com\shalk\blog>cobra add delete
delete created at D:\code\github.com\shalk\blog
D:\code\github.com\shalk\blog>cobra add list
list created at D:\code\github.com\shalk\blog
D:\code\github.com\shalk\blog>cobra add edit
edit created at D:\code\github.com\shalk\blog
ログイン後にコピー
New.go、delete.go、list.go、edit.go関数コードの追加D:\code\github.com\shalk\blog>cobra add new new created at D:\code\github.com\shalk\blog D:\code\github.com\shalk\blog>cobra add delete delete created at D:\code\github.com\shalk\blog D:\code\github.com\shalk\blog>cobra add list list created at D:\code\github.com\shalk\blog D:\code\github.com\shalk\blog>cobra add edit edit created at D:\code\github.com\shalk\blog
new.go
var newCmd = &cobra.Command{ Use: "new", Short: "create new post", Long: `create new post `, Args: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return errors.New("requires a color argument") } return nil }, Run: func(cmd *cobra.Command, args []string) { fileName := "posts/" + args[0] err := os.Mkdir("posts", 644) if err != nil { log.Fatal(err) } _, err = os.Stat( fileName) if os.IsNotExist(err) { file, err := os.Create(fileName) if err != nil { log.Fatal(err) } log.Printf("create file %s", fileName) defer file.Close() } else { } }, }
var listCmd = &cobra.Command{ Use: "list", Short: "list all blog in posts", Long: `list all blog in posts `, Run: func(cmd *cobra.Command, args []string) { _, err := os.Stat("posts") if os.IsNotExist(err) { log.Fatal("posts dir is not exits") } dirs, err := ioutil.ReadDir("posts") if err != nil { log.Fatal("read posts dir fail") } fmt.Println("------------------") for _, dir := range dirs { fmt.Printf(" %s\n", dir.Name() ) } fmt.Println("------------------") fmt.Printf("total: %d blog\n", len(dirs)) }, }
var deleteCmd = &cobra.Command{ Use: "delete", Short: "delete a post", Long: `delete a post`, Args: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return errors.New("requires a color argument") } if strings.Contains(args[0],"/") || strings.Contains(args[0],"..") { return errors.New("posts name should not contain / or .. ") } return nil }, Run: func(cmd *cobra.Command, args []string) { fileName := "./posts/" + args[0] stat, err := os.Stat(fileName) if os.IsNotExist(err) { log.Fatalf("post %s is not exist", fileName) } if stat.IsDir() { log.Fatalf("%s is dir ,can not be deleted", fileName) } err = os.Remove(fileName) if err != nil { log.Fatalf("delete %s fail, err %v", fileName, err) } else { log.Printf("delete post %s success", fileName) } }, }
PS D:\code\github.com\shalk\blog> go build -o blog.exe . PS D:\code\github.com\shalk\blog> .\blog.exe list ------------------ ------------------ total: 0 blog PS D:\code\github.com\shalk\blog> .\blog.exe new blog1.md 2020/07/26 22:37:15 create file posts/blog1.md PS D:\code\github.com\shalk\blog> .\blog.exe new blog2.md 2020/07/26 22:37:18 create file posts/blog2.md PS D:\code\github.com\shalk\blog> .\blog.exe new blog3.md 2020/07/26 22:37:20 create file posts/blog3.md PS D:\code\github.com\shalk\blog> .\blog list ------------------ blog1.md blog2.md blog3.md ------------------ total: 3 blog PS D:\code\github.com\shalk\blog> .\blog delete blog1.md 2020/07/26 22:37:37 delete post ./posts/blog1.md success PS D:\code\github.com\shalk\blog> .\blog list ------------------ blog2.md blog3.md ------------------ total: 2 blog PS D:\code\github.com\shalk\blog> ls .\posts\ 目录: D:\code\github.com\shalk\blog\posts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2020/7/26 22:37 0 blog2.md -a---- 2020/7/26 22:37 0 blog3.md PS D:\code\github.com\shalk\blog>
以上が一般的な Golang ライブラリ cobraの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

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

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Go ではファイルを安全に読み書きすることが重要です。ガイドラインには以下が含まれます。 ファイル権限の確認 遅延を使用してファイルを閉じる ファイル パスの検証 コンテキスト タイムアウトの使用 これらのガイドラインに従うことで、データのセキュリティとアプリケーションの堅牢性が確保されます。

Go データベース接続の接続プーリングを構成するにはどうすればよいですか?データベース接続を作成するには、database/sql パッケージの DB タイプを使用します。同時接続の最大数を制御するには、MaxOpenConns を設定します。アイドル状態の接続の最大数を設定するには、ConnMaxLifetime を設定します。

GoLang フレームワークと Go フレームワークの違いは、内部アーキテクチャと外部機能に反映されています。 GoLang フレームワークは Go 標準ライブラリに基づいてその機能を拡張していますが、Go フレームワークは特定の目的を達成するための独立したライブラリで構成されています。 GoLang フレームワークはより柔軟であり、Go フレームワークは使いやすいです。 GoLang フレームワークはパフォーマンスの点でわずかに優れており、Go フレームワークはよりスケーラブルです。ケース: gin-gonic (Go フレームワーク) は REST API の構築に使用され、Echo (GoLang フレームワーク) は Web アプリケーションの構築に使用されます。

JSON データは、gjson ライブラリまたは json.Unmarshal 関数を使用して MySQL データベースに保存できます。 gjson ライブラリは、JSON フィールドを解析するための便利なメソッドを提供します。json.Unmarshal 関数には、JSON データをアンマーシャリングするためのターゲット型ポインターが必要です。どちらの方法でも、SQL ステートメントを準備し、データをデータベースに永続化するために挿入操作を実行する必要があります。

ベスト プラクティス: 明確に定義されたエラー タイプ (エラー パッケージ) を使用してカスタム エラーを作成する 詳細を提供する エラーを適切にログに記録する エラーを正しく伝播し、非表示または抑制しないようにする コンテキストを追加するために必要に応じてエラーをラップする

FindStringSubmatch 関数は、正規表現に一致する最初の部分文字列を検索します。この関数は、最初の要素が一致した文字列全体で、後続の要素が個々の部分文字列である、一致する部分文字列を含むスライスを返します。コード例: regexp.FindStringSubmatch(text,pattern) は、一致する部分文字列のスライスを返します。実際のケース: 電子メール アドレスのドメイン名を照合するために使用できます。たとえば、email:="user@example.com", pattern:=@([^\s]+)$ を使用してドメイン名を照合します。 [1]。

Go フレームワークで一般的なセキュリティ問題に対処する方法 Web 開発で Go フレームワークが広く採用されているため、そのセキュリティを確保することが重要です。以下は、一般的なセキュリティ問題を解決するための実践的なガイドであり、サンプル コードも含まれています。 1. SQL インジェクション SQL インジェクション攻撃を防ぐには、プリペアド ステートメントまたはパラメータ化されたクエリを使用します。例: constquery="SELECT*FROMusersWHEREusername=?"stmt,err:=db.Prepare(query)iferr!=nil{//Handleerror}err=stmt.QueryR

バックエンド学習パス:フロントエンドからバックエンドへの探査の旅は、フロントエンド開発から変わるバックエンド初心者として、すでにNodeJSの基盤を持っています...
