Suggested Init Script Before Coding in Golang
Suggested Init Script
The very basic variable you need to lookout for in go is the environment variable $GOPATH
.
In Unix/Linux-based systems it is by default in ~/go.
My preference is to put it in a directory where my go code exists. So here's a short shell script I use:
1#!/bin/bash
2
3## Enforce calling "init.sh" from within project directory.
4##
5init_call_check=$(dirname $0)
6if [[ "$init_call_check" != ".." ]]; then
7 echo "ERROR: 'init.sh' must be called from within project directory."
8 echo ' Call MUST be ../init.sh <GOPATH_PREF>'
9 echo " GOPATH_PREF defaults to 'inside'. Otherwise, use 'outside'"
10 exit 1
11fi
12
13## Check user preference
14user_pref=${1:-"inside_projectdir"}
15
16## Default preferred location is inside "/path/to/code/go/<project_dir_here>"
17## Otherwise, use "outside_projectdir" so GOPATH becomes "/path/to/code/go"
18GOPATH_PREF='inside_projectdir'
19[[ "$user_pref" =~ "outside" ]] && GOPATH_PREF='outside_projectdir'
20
21if [[ -z $GOPATH ]]; then
22
23 if [[ "$GOPATH_PREF" = "inside_projectdir" ]]; then
24 export GOPATH=$(pwd)
25 export PATH=$GOPATH:$PATH
26 else
27 export GOPATH=$(dirname $(pwd))
28 export PATH=$GOPATH:$PATH
29 fi
30
31 echo '--------------------------------------------------'
32 echo 'Go environment now defined!'
33 echo " GOPATH => $GOPATH"
34 echo "Type 'exit' to remove the Go environment variable."
35 echo '--------------------------------------------------'
36 bash ## Run a subshell to retain the defined environment variables above.
37 echo "[NOTICE] Exited Go Environment. GOPATH unset."
38 echo
39else
40 echo "WARNING: GOPATH already defined. Use 'exit' to redefine."
41 echo " GOPATH => $GOPATH"
42 exit 1
43fi
bash
High Level Structure(s)
1/path/to/coding/go
2 |
3 +--- init.sh ## this is common to projects
4 +--- project1 ## project. Call init inside as ../init
5 +--- project2 ## project. Call init inside as ../init
6 | ...
7 +--- projectN ## project. Call init inside as ../init
If there's a need for GOPATH to be outside the project directory, just say so as follows: