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)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241643닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241621닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241635닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241631오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241646디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241646오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241744닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241747디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242625오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241820닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241620Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241955닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241693닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...