uzullaがブログ

uzullaがブログです。

GoのバイナリをPHPスクリプトとしても扱う

codehex.hateblo.jp

$ ./main
This is Go world!!
今度は Perl で実行してみましょう

$ perl -x ./main
Hello, Perl World!!
ワオ!!

ほほう。

phpではどうすべきか

-xオプションはないが、<?phpまではSTDOUTにそのまま出力されてコードとしては解釈されません。なので…

$ cat main.go
package main

import (
    "fmt"
    "io/ioutil"
)

const script = `<?php
file_put_contents("php://stderr", "This is PHP world!!!".PHP_EOL);
__halt_compiler();
`

func init() {
    ioutil.Discard.Write([]byte(script))
}

func main() {
    fmt.Println("This is Go world!!")
}

$ go build -o main main.go

$ ./main
This is Go world!!

$ php ./main 2>&1 > /dev/null
This is PHP world!!!

こちらからは以上です。

なお、このエントリは8分でかかれました。

(が、やり方をちゃんと理解してなかったので、なおしました…)

f:id:uzulla:20190702191852p:plain