원 글은 Cloudflare의 Using Go as a scripting language in Linux
TLDR
Linux 커널에는 /proc/sys/fs/binfmt_misc 라는 기능이 있고, 지정 확장자/매직 코드에 대해서 지정 인터프리터를 실행할 수 있다.
이 기능을 사용하여 Go의 소스 파일을 ./helloscript.go 로 실행 할 수 있다.
예로 사용하는 Go 소스 파일은 아래와 같다. shebang 등은 필요 없다
package main import ( "fmt" "os" ) func main() { s := "world" if len(os.Args) > 1 { s = os.Args[1] } fmt.Printf("Hello, %v!", s) fmt.Println("") if s == "fail" { os.Exit(30) } } |
하는 방법
Using Go as a scripting language in Linux 에 적혀 있는 대로.
# binfmt_misc 기능이 유효한지 확인 $ mount | grep binfmt_misc systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=27,pgrp=1,timeout=0,minproto=5,maxproto=5,direct) # 프로세스의 EXIT STATUS가 잘 OS에 넘겨지도록 하기 위해 랩퍼로서 gorun을 넣는다 $ go get github.com/erning/gorun $ sudo mv ~/go/bin/gorun /usr/local/bin/ # binfmt_misc 설정 $ echo ':golang:E::go::/usr/local/bin/gorun:OC' | sudo tee /proc/sys/fs/binfmt_misc/register :golang:E::go::/usr/local/bin/gorun:OC # 스크립트에 실행 속성을 붙인다 $ chmod u+x helloscript.go # 실행한다 (완성!) $ ./helloscript.go Hello, world! |