This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Programming

Programming Languages

1 - golang

  • Go is an opensource programming language developed by Google.
  • Go provides garbage collection, type safety, dynamic-typing capability.
  • Go provides a rich standard library, called as packages (Standard Libraries) - goPackages

Getting Started

  1. How to install and set up Go
  2. How to set custom goPATH
  3. How to write Go Code
  4. Dependency Management with go modules
# gopath can be any directory on your system  
Edit your `~/.bash_profile` and add the line: `export GOPATH=$HOME/go`  
source your bash_profile `source ~/.bash_profile`
# Set the GOBIN path to generate a binary file when go install is executed.
 `export GOBIN=$HOME/go/bin`

Environment variables

Command to check environment variables go env

Workspaces

Workspace in go is a directory hierarchy with 3 directories at its root

  • src : The src directory contains source code.The path below src determines the import path or executable name.
  • pkg : contains go installed package objects. Each target operating system and architecture pair has its own subdirectory of pkg
    format: pkg/GOOS_GOARCH
    example: pkg/linux_amd64
  • bin : contains executable binaries.

IDE for golang

Visual Studio Code
GoLand

Getting help with go commands

go provides extensive command line help by simply using help option as argument, For any help related to go , use

go help <command>

examples:

go help build

go help install

go help clean

go help gopath

How to build go executables for different architectures

The go build command allows us to create executables for all golang supported architectures. To build executables for different architectures GOOS and GOARC arguments need to be set accordingly.

env GOOS=target-OS GOARCH=target-architecture go build <package-import-path>
env GOOS=windows GOARCH=amd64 go build <path_to_go_src>

To get a complete list of all supported platforms and architectures, use the command : go tool dist list

sriram@optimus-prime:~$ go tool dist list
android/386
android/amd64
android/arm
android/arm64
darwin/386
darwin/amd64
darwin/arm
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/mips
linux/mips64
linux/mips64le
linux/mipsle
linux/ppc64
linux/ppc64le
linux/s390x
nacl/386
nacl/amd64p32
nacl/arm
netbsd/386
netbsd/amd64
netbsd/arm
openbsd/386
openbsd/amd64
openbsd/arm
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
windows/386
windows/amd64

References

golang Tutorial
golang wiki page
curated list of awesome Go frameworks

2 - Python

2.1 - Getting Started

How to install Python3 in Debian

# Install prerequisites
$ sudo apt-get install build-essential 
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev zlib1g-dev

# Download and extract python source tar
cd /tmp
wget https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tar.xz
tar -xvf Python-3.8.5.tar.xz
cd Python-3.8.5
./configure --prefix=/appl/Python_3_8_5 --enable-optimizations
make
make install

Dictionary

# load json file 
with open('data_file.json') as json_file: 
    data = json.load(json_file) 
 
print(json.dumps(data,indent=4)) 

for groups in data['values']: 
     print(groups.items()) 

Class

class MyClass: 
    def __init__(self,f_name,l_name): 
        print("MyClass is instantiated successfully") 
        print(f'{f_name}_{l_name}') 
        self.f_name = f_name 
        self.l_name = l_name 
 
if __name__ == '__main__': 
    print('file is called directly') 
else: 
    print('test2 file is imported') 
 
print(MyClass.__dict__) 

How to parse JSON

# https://docs.atlassian.com/bitbucket-server/rest/6.10.0/bitbucket-rest.html 
# https://pynative.com/parse-json-response-using-python-requests-library/ 
 
import requests 
 
session = requests.Session() 
limit = 25 
start = 0 
isLastPage = False 
json_response = [] 
admin_groups = [] 
 
try: 
    while not isLastPage: 
        url = f'https://bitbucket_url:7999/rest/api/1.0/admin/groups?limit={limit}&start={start}'
        # print(url) 
        r = session.get(url,auth=('USer_ID', 'Passwd')) 
        json_response.append(r.json()) 
        isLastPage = r.json()['isLastPage'] 
        if isLastPage == True: 
            break 
        start = r.json()['nextPageStart'] 
except Exception as err: 
    print(f'error: {err}') 
 
# json_response is a list with dictionary of values 
# iterate through list and get the dictionary 
for item in json_response: 
    for names in item['values']: 
        admin_groups.append(names['name'])      # Add the admin group names to list 
 
# Total number of groups 
print(f'Total Number of groups : {len(admin_groups)}') 
# iterate through admins list and print the admin group names 
for admin in admin_groups: 
    print(admin)

Argument Parsing - Flags

import requests 
import argparse 
 
 
def check_app_status(url): 
    r = requests.get(url) 
    try: 
        response = r.json() 
    except Exception as e: 
        print(f'Exception occured : {e}') 
    if (r.status_code == 200 and response['state'] == "RUNNING"): 
        print(f'Application is up and running') 
    else: 
        print(f'Application is not reachable') 

 
def init_argument_parser(argument_list=None): 
    parser = argparse.ArgumentParser() 
    parser.add_argument('-url', '--url', help='URL of Application ', required=True) 
    return parser.parse_args() 
 
if __name__ == '__main__': 
    args = init_argument_parser() 
    # print(f'{args.url}') 
    check_app_status(args.url)