티스토리 뷰

Go

1. Go CLI - Go Developer Road Map

Miles 2021. 2. 1. 17:11

Go 개발자 로드맵의 첫 번째 챕터, Go CLI 프로그램을 만드는 방법입니다. CLICommand Line Interface의 약자로, 터미널을 통해 컴퓨터와 상호작용하는 방식을 말합니다.

Go CLI 프로그램을 만드는 여러 패키지가 있습니다.

Go의 내장 패키지인 flags가 있지만 cobra를 사용하면 더욱 빠르고 쉽게 CLI 프로그램을 개발할 수 있습니다.

설치

다음과 같이 go get을 사용하여 cobra를 설치할 수 있습니다. -u는 최신 버전을 설치하는 플래그입니다.

go get -u github.com/spf13/cobra

또한 다음 명령어로 Code Generator를 설치하여 cobra를 쉽게 적용할 수 있습니다.

go get -u github.com/spf13/cobra/cobra

Cobra Generator 사용하기

Cobra Generator의 init 명령어로 새로운 프로젝트 템플릿을 생성할 수 있습니다.

cobra init --pkg-name github.com/spf13/newApp

그리고 add 명령어로 command를 추가할 수 있습니다.

cobra add version

명령어 추가

package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
)

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. 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.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("version called")
	},
}

func init() {
	rootCmd.AddCommand(versionCmd)
}

cobraCommand 구조체를 사용하여 Use에 사용할 command를, Short에 짧은 설명, Long에 자세한 설명을 작성할 수 있습니다. 그리고 이렇게 추가한 command를 루트 command에 추가해줍니다. 그리고 가장 중요한 것은 Run에 명령어를 호출했을 때 실행할 작업을 작성해주면 됩니다. version의 경우 현재 프로그램의 버전을 출력하는 함수를 작성하면 됩니다.

배포하기

Go로 작성된 프로그램은 go build를 사용하여 배포할 수 있습니다.

go build

이 명령어를 실행하면 .exe 파일이 생성되는데 이 바이너리 파일을 실행하면 CLI로 사용할 수 있습니다.

댓글
공지사항
최근에 올라온 글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함