Created
February 8, 2018 17:07
-
-
Save roscopecoltran/0ac9fbab24ee220ac476a7ffd1f8a0da to your computer and use it in GitHub Desktop.
goscript - run Go golang in scripts!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!./goscript | |
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
fmt.Println("hello"); | |
for i, arg := range os.Args { | |
fmt.Printf("arg[%d]='%s'\n", i, arg); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
unset TEMP_GOSCRIPT_DIR GOSCRIPT | |
GOARGS=() ARGS=() | |
cleanup() { | |
RES=$? | |
rm -rf "$TEMP_GOSCRIPT_DIR" | |
exit $RES | |
} | |
trap 'cleanup' INT QUIT TERM | |
filter() { awk '( NR!=1 || !/^#!/ ) && !/^package /; BEGIN{ print "package main" }' "$@"; } | |
TEMP_GOSCRIPT_DIR="$(mktemp -d -t XXXXXXXXXX)" | |
TEMP_GOSCRIPT="$TEMP_GOSCRIPT_DIR/main$$.go" | |
for ((I=1; I<=$#; ++I)); do | |
ARG="$(eval echo \$$I)" | |
case "$ARG" in | |
-*) [ -z "$GOSCRIPT" ] && GOARGS+=("$ARG") || ARGS+=("$ARG") ;; | |
*) [ -t 0 ] && [ -z "$GOSCRIPT" ] && GOSCRIPT=("$ARG") || ARGS+=("$ARG") ;; | |
esac | |
done | |
{ | |
if [ -z "$GOSCRIPT" ]; then | |
filter | |
else | |
filter < "$GOSCRIPT" | |
fi ;} > "$TEMP_GOSCRIPT" | |
go run "${GOARGS[@]}" "$TEMP_GOSCRIPT" "${ARGS[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment