프로그래밍/GO

모듈 호출하기 Call your code from another module

autostar 2023. 2. 21.

목차

반응형

모듈 만들기에 이어서

https://everyauto.tistory.com/24

[모듈 만들기 creating a module

모듈은 간단하게 말하자면 패키지를 모아 놓은 것이라고 보면 됩니다. 지난시간에 https://everyauto.tistory.com/22 [Golang 처음부터 시작해보기 최근들어 고랭 공부를 다시 시작해 보면서 기록을 좀 남

everyauto.tistory.com](https://everyauto.tistory.com/24)

이번엔 모듈을 호출해서 사용하는 것을 해보겠습니다..

greetings 와 hello 디렉토리를 생성후 코드를 작성했습니다.

모듈 호출하기 Call your code from another module

이렇게 준비된 상태에서

hello 디렉토리로 이동합니다.

package greetings
import "fmt"
func Hello(name string) string {
message := fmt.Sprintf("Hi %s. welcome!", name)
return message
}
view raw greetings.go hosted with ❤ by GitHub
package main
import (
"fmt"
"test/greetings"
)
func main() {
message := greetings.Hello("autostar")
fmt.Println(message)
}
view raw hello.go hosted with ❤ by GitHub

각 디렉토리에서 go.mod 커맨드를 이용해서 모듈을 만들어줍니다.

go mod init test/greetings
go mod init test/hello

그런데 문제가 있습니다.

모듈은 우리가 적어준 test 에서 소스를 찾습니다. 그리고 못찾는다고 에러메시지를 내보내죠

로컬에서 사용하려면 이 소스를 test 에서 찾지 말고 로컬에서 찾으라고 알려줘야 합니다. 그 작업을 go.mod 커맨드로 합니다.

go mod edit -replace test/greetings=../greetings

이렇게 하면 

모듈 호출하기 Call your code from another module

go.mod 파일에 해당 내용이 업데이트 됩니다.

 

다시 

모듈 호출하기 Call your code from another module

실행 해보면 안된다고 컴플레인 거는데 떠 있는 메시지대로 커맨드 입력 해준뒤 정상 작동 됩니다. 

만약 test 가 아니고 example.com 이었다면 go get 커맨드까지 입력하지 않아도 됩니다. 

go mod tidy 커맨드로 모듈을 찾기도 합니다. 

반응형

댓글