Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 구성

예전에 Go 언어를 위한 LiteIDE에서의 개발 환경을 다뤘었는데요,

go install: no install location for directory [...경로...] outside GOPATH
; https://www.sysnet.pe.kr/2/0/11097

대세가 Visual Studio Code인 것 같군요. ^^ 그래서 다시 처음부터 구성해 보겠습니다.

우선, Go 언어를 (msi도 좋겠지만) zip 파일 버전으로 다운로드하고,

Go - Downloads
; https://golang.org/dl/

go1.15.14.windows-amd64.zip
; https://golang.org/dl/go1.15.14.windows-amd64.zip

"D:\go" 디렉터리에 풀어놓겠습니다. 이후 PATH 환경 변수에 해당 디렉터리를 추가합니다.

PATH 환경 변수에 경로 추가: d:\go\bin

자, 이제 프로젝트 경로를 정하고,

프로젝트 경로: d:\mywork

해당 디렉터리에 hello.go 파일을 다음의 내용으로 채워준 다음,

package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

Visual Studio Code를 실행시켜 "d:\mywork" 디렉터리를 "File" / "Open Folder... (Ctrl+K, Ctrl+O)" 메뉴로 엽니다.




일단 위의 단계까지 끝냈으면, 이제 Visual Studio Code에 Go 언어를 위한 확장(Go for Visual Studio Code)을 설치해야 합니다. 이 과정은 단순하게, hello.go 파일을 Code 내에서 열면 자동으로 "Do you want to install the recommended extensions for Go?"라는 메시지와 함께 설치 여부를 묻는 창이 뜹니다.

"Install"을 선택해 주면 이어서 다음의 메시지와 함께,

The "gopls" command is not available. Run "go get -v golang.org/x/tools/gopls" to install.

다시 설치 여부를 묻는데요, 역시 "Install"을 선택하면 아래와 같은 식의 메시지와 함께 정상적으로 설치가 됩니다.

Tools environment: GOPATH=%USERPROFILE%\go
Installing 1 tool at %USERPROFILE%\go\bin in module mode.
  gopls

Installing golang.org/x/tools/gopls (%USERPROFILE%\go\bin\gopls.exe) SUCCEEDED

All tools successfully installed. You are ready to Go :).

자, 그럼 이제 hello.go 파일을 실행하기 위해 "F5" 키를 눌러 봅니다. 그럼 다시 아래와 같은 메시지가 뜨고,

The "dlv" command is not available. Run "go get -v github.com/go-delve/delve/cmd/dlv" to install.

"Install"을 누르면 아래의 메시지와 함께,

Tools environment: GOPATH=%USERPROFILE%\go
Installing 1 tool at %USERPROFILE%\go\bin in module mode.
  dlv

Installing github.com/go-delve/delve/cmd/dlv (%USERPROFILE%\go\bin\dlv.exe) SUCCEEDED

All tools successfully installed. You are ready to Go :).

환경 구성이 완료됩니다. 다시 한번 F5 키를 눌러 실행하면 잠시 후 "DEBUG CONSOLE" 화면에 "Hello World!"가 출력되는 것을 확인할 수 있습니다.

go_with_code_0.png




참고로, Visual Studio Code의 Go 확장이 "F5" 키를 눌렀을 때 (윈도우의 경우) EXE를 생성해 실행하는 구조는 아닙니다. 임시로 프로젝트 디렉터리("d:\mywork") 하위에 "__debug_bin" 파일을 생성하고 그것을 실행해 주는데요.

따라서 대충 개발이 완료되고 나면 EXE 파일은 별도로 생성해야 하는데, 이를 위해 단순하게 "Ctrl + `" 키를 눌러 TERMIANL 창을 열어 "go build" 명령어를 실행하면 됩니다.

go_with_code_1.png

그럼, "d:\mywork" 디렉터리 내에 "mywork.exe" 파일이 생성됩니다. 당연히 이렇게 생성한 파일은 다른 컴퓨터에 그대로 복사해 실행할 수 있습니다.

만약 "d:\mywork"에 exe 파일이 생성되는 것이 영 탐탁지 않다면 go build 명령어에 다음과 같이 옵션을 추가해도 좋습니다.

// 명령을 실행하기 전 반드시 bin 디렉터리를 만들어 둠
// 그렇지 않으면 "bin"이라는 파일명으로 출력

PS D:\mywork> go build -o bin

그리고 이런 작업을 "Ctrl+Shift+B" 키로 수행하고 싶다면, "Build Task(.vscode\tasks.json)"에 다음과 같이 명령을 입력해 두면 됩니다.

{
    // Build and run Golang projects in VS Code
    // https://robertbasic.com/blog/build-and-run-golang-projects-in-vs-code/
    // 명령을 실행하기 전, 반드시 하위에 bin 디렉터리를 만듭니다.
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Go Build",
            "type": "shell",
            "command": "go build -o bin",
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

(물론 F5 키로 __debug_bin 실행이 가능하지만) 만약 빌드된 EXE 결과물을 Ctrl+Shift+B 키로 (빌드와 함께) 실행까지 하고 싶다면 "command"를 다음과 같은 식으로 변경하면 될 텐데,

"command": "go build -o bin && .\\bin\\mywork",

아마 잘 되는 분도 있는 반면 경우에 따라 아래와 같은 오류가 발생하는 분도 있을 것입니다.

> Executing task: go build -o bin && ./bin/mywork <

At line:1 char:17
+ go build -o bin && ./bin/mywork
+                 ~~
The token '&&' is not a valid statement separator in this version.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx 
   ception
    + FullyQualifiedErrorId : InvalidEndOfLine
 
The terminal process "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -Command go build -o bin && ./bin/mywork" terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

왜냐하면 위의 화면을 보면 해당 명령어를 실행하는 환경이 powershell.exe로 되어 있기 때문에 && 구문에 오류가 발생하는 것입니다. 따라서, 이럴 때는 "command"를 이렇게 변경해야 합니다.

// Can I get "&&" or "-and" to work in PowerShell?
// https://stackoverflow.com/questions/563600/can-i-get-or-and-to-work-in-powershell

"command": "(go build -o bin); if ($?) { ./bin/mywork }",

이후 Ctrl+Shift+B 키를 누르면 "Build and Run"의 동작이 수행됩니다.




그나저나 그동안 변경 사항이 좀 있었군요. ^^ 예전에는 "GOROOT" 환경 변수를 정의해 Go 설치 경로(위의 글에서는 d:\go)를 설정하지 않으면 "go version" 같은 명령어 수행 시 오류가 발생했는데,

C:\temp> go version
go: cannot find GOROOT directory: c:\go

이제는 GOROOT 없이도 잘 동작합니다. 실제로 "go env" 명령을 내려 보면 예전에는 비어 있던 GOROOT, GOPATH 같은 환경 변수들이 이제는 다음과 같이 기본값으로 채워져 있습니다.

c:\temp> go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=%USERPROFILE%\AppData\Local\go-build
set GOENV=%USERPROFILE%\AppData\Roaming\go\env
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=%USERPROFILE%\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=%USERPROFILE%\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=D:\go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=D:\go\pkg\tool\windows_amd64
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=%USERPROFILE%\AppData\Local\Temp\go-build014406382=/tmp/go-build -gno-record-gcc-switches

진작에 저랬어야죠. ^^;

이런 상태에서 Go 컴파일을 하면 전역적으로 GOPATH(%USERPROFILE%\go) 하위에 bin, pkg 디렉터리가 생성됩니다. 만약 저렇게 전역 관리가 싫다면 GOPATH를 별도로 프로젝트 단위로 설정해,

SET GOPATH=d:\mywork

d:\mywork 하위에 bin, pkg 디렉터리를 구성하게 둘 수도 있습니다.




Go 컴파일러는 윈도우에서 리눅스용, 리눅스에서 윈도우용 바이너리를 쉽게 만들 수가 있군요. ^^
D:\mywork> set GOOS=linux // MacOS: darwin
D:\mywork> set GOARCH=amd64 // 32비트: 386,  M1 chip: arm64
D:\mywork> go build // 리눅스용 실행 파일 생성
D:\mywork> wsl // 윈도우 -> WSL 전환

/mnt/d/mywork# ./mywork // 생성된 ELF 파일 실행

/mnt/d/mywork# export GOOS=windows
/mnt/d/mywork# export GOARCH=amd64
/mnt/d/mywork# export go build // 윈도우용 실행 파일 생성
/mnt/d/mywork# exit // WSL -> 윈도우 전환
D:\mywork> mywork.exe // 생성된 EXE 실행

D:\mywork> go tool dist list
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
illumos/amd64
js/wasm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/mips
linux/mips64
linux/mips64le
linux/mipsle
linux/ppc64
linux/ppc64le
linux/riscv64
linux/s390x
netbsd/386
netbsd/amd64
netbsd/arm
netbsd/arm64
openbsd/386
openbsd/amd64
openbsd/arm
openbsd/arm64
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
windows/386
windows/amd64
windows/arm




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/20/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-07-29 10시13분
Learning Go by examples: Introduction
; https://dev.to/aurelievache/learning-go-by-examples-introduction-448n

Learning Go by examples: part 2 - Create an HTTP REST API Server in Go
; https://dev.to/aurelievache/learning-go-by-examples-part-2-create-an-http-rest-api-server-in-go-1cdm

Learning Go by examples: part 3 - Create a CLI app in Go
; https://dev.to/aurelievache/learning-go-by-examples-part-3-create-a-cli-app-in-go-1h43
정성태

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13498정성태12/23/20232810닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232290오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232305Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232315Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232497Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232535닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232259개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232231Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232337개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232130개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232065오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232379개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232193개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232159개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232295닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232809닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232261개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232572개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232281개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232464닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232199닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232257닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232116개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232302닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232132C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...