• Stars
    star
    1,498
  • Rank 31,328 (Top 0.7 %)
  • Language
    Go
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Go(lang) examples - (explain the basics of #golang)

Go Examples

DOI
Go Report Card
License: MIT

NEW: now with an online live editor with Golang support. Try out and edit the examples directly in the browser: SimonWaldherr/golang-benchmarks Online Editor

If you liked this project, you may also like my golang-benchmarks repository:
SimonWaldherr/golang-benchmarks - GitHub
my gotools repository:
SimonWaldherr/gotools - GitHub
my sql-examples repository:
SimonWaldherr/sql-examples - GitHub
or my rpi-examples repository:
SimonWaldherr/rpi-examples - GitHub

About

These examples explain the basics of Golang. There will be more examples from time to time.

if you like, feel free to add more Golang examples. Many thanks to all contributors.

Install go(lang)

with homebrew:

sudo brew install go

with apt-get:

sudo apt-get install golang

install Golang manually or compile it yourself

Examples

The examples are divided into three levels of difficulty. The Beginner section contains very easy examples, starting with Hello World but also containing a few easy algorithms. The Advanced section uses more complicated features of Golang. Finally, the Expert section contains applications like telnet-clients or http-server (even with SSL). If you want even more Golang examples, you can take a look at my other go repositories at GitHub:

All of them are published as free and open source software.

If all of this is even not enough for you, you can take a look at the following websites:

Beginner

To execute a Golang program, write go run at the cli followed by the name of the file.
You also can convert the file to a binary executable program by the command go build.
If you know #!, also known as Shebang, there is an equivalent for go: //usr/bin/env go run $0 $@ ; exit

Print Hello World with comments (Golang Playground)

go run HelloWorld.go

Print Hello World with comments (shebang version)

./HelloWorldShebang.go

Declare variables and print them (Golang Playground)

go run var.go

Various ways (and styles) to print variables (Golang Playground)

go run printf.go

If statement in Golang (Golang Playground)

go run if.go Hello

Declare array and print its items (Golang Playground)

go run array.go

Declare your own functions (Golang Playground)

go run function.go

Do something multiple times (Golang Playground)

go run for.go

Read via cli provided input data (Golang Playground)

go run args.go string string2

Read via cli provided input data (Golang Playground)

go run input.go

Or scan for it (Golang Playground)

go run scan.go

Read named argument input data (Golang Playground)

go run flag.go

Return the working directory (Golang Playground)

go run dir.go

Return the current time/date in various formats (Golang Playground)

go run time.go

Return pseudo random integer values (Golang Playground)

go run random.go

Concat strings in two different ways (Golang Playground)

go run cat.go

Modulo operation finds the remainder of division (Golang Playground)

go run modulo.go

Split a string by another string and make an array from the result (Golang Playground)

go run split.go

An example implementation of the Ackermann function (Golang Playground)

go run ackermann.go

An example implementation of the Euclidean algorithm (Golang Playground)

go run euklid.go

Submit a function as argument (Golang Playground)

go run functioncallback.go

A function returned by a function (Golang Playground)

go run functionclosure.go

A function with an unknown amount of inputs (variadic function) (Golang Playground)

go run functionvariadic.go

Empty interface as argument (You Don't Know Type) (Golang Playground)

go run interface.go

Execute Shell/Bash commands and print its output values (Golang Playground)

go run shell.go

Make structs (objects) which have functions (Golang Playground)

go run oop.go

Dependency injection for easier testing

cd beginner/di
go test

Hashing (md5, sha) in go (Golang Playground)

go run hashing.go

Advanced

Benchmarking example (using JSON marshal and unmarshal for the sample) (Golang Playground) From the root directory ($GOPATH/github.com/SimonWaldherr/golang-examples), run this command:

go test -bench=. -benchmem advanced/json_bench/main_test.go

Make pipeable unix applications with os.Stdin (Golang Playground)

go run pipe.go

AES-GCM encryption example (Golang Playground)

go run aesgcm.go

Bcrypt hashing example (Golang Playground) Please install package golang.org/x/crypto/bcrypt before run this file by running go get golang.org/x/crypto/bcrypt

go run bcrypt.go

Search element is exist in arrays or not (Golang Playground)

go run in_array.go

Calculate triangles (Golang Playground)

go run pythagoras.go (float|?) (float|?) (float|?)

Read from stdin (but don't wait for the enter key)

go run getchar.go

Wait and sleep (Golang Playground)

go run wait.go

Last in - first out - example (Pop and push in Golang) (Golang Playground)

go run lifo.go

Split a string via regular expression and make an array from the result (Golang Playground)

go run regex.go

More advanced regex (with time and dates) (Golang Playground)

go run regex2.go

Use my golibs regex package and have fun (Golang Playground)

go run regex3.go

Calculate and print the fibonacci numbers (Golang Playground)

go run fibonacci.go

Calculate and print the requested (32th) prime number (Golang Playground)

go run prime.go 32

Do things with numbers, strings and switch-cases (Golang Playground)

go run numbers.go

Use a template to create and fill documents (this example uses LaTeX) (Golang Playground)

go run template.go
pdflatex -interaction=nonstopmode template_latex.tex

Start a ticker (do things periodically)

go run ticker.go

Do something in case of a timeout (Golang Playground)

go run timeout.go

Convert go object to json string (Golang Playground)

go run json.go

Run unix/shell commands in go apps

go run exec.go

Compress by pipe

go run compress.go

Compress by file

go run compress2.go

Parse CSV (Golang Playground)

go run csv.go

Convert CSV to a Markdown table (Golang Playground)

go run csv2md.go

Parse a XML string into a Struct with undefined Fields (Golang Playground)

go run xml.go

Run a self killing app

go run suicide.go

GoCV : hello video

go run hello_video.go

GoCV : face detection

go run face_detect.go 0 model/haarcascade_frontalface_default.xml

Run the example for generic (Golang Playground)

go run generic.go

Expert

Calculate π with go (leibniz, euler and prime are running until you stop it via CTRL+C)

go run pi2go.go leibniz
go run pi2go.go euler
go run pi2go.go prime

Calculate π with go - same as above - but with live output (based on gcurses)

go run pi2go-live.go leibniz
go run pi2go-live.go euler
go run pi2go-live.go prime

List files in working directory

go run explorer.go

run assemply code from golang

go run assembly.go

run C code from golang

go run cgo.go

generate Go code with golang templates

go run codegen.go

Convert from rgb to hsl (Golang Playground)

go run color.go

Telnet with Golang

go run telnet.go

The smallest Golang http server

go run httpd.go

Secure Golang http server

go run httpsd.go

The smallest Golang http proxy

go run proxy.go

Read and write cookies

go run cookies.go

Demonstrate the power of multithreading / parallel computing you have to set GOMAXPROCS to something greater than 1 to see any effect

export GOMAXPROCS=8
time go run parallel.go true
time go run parallel.go false

A dynamic amount of channels

time go run dynparallel.go 8

Run the compiler and comment each line which contains an error

go build gocomment.go
./gocomment go-app.go

Convert a image to a grayscale and to a color inverted image

go run image.go

Generate an image with three colored circles (with intersection)

go run image2.go

Generate an image representing the Mandelbrot fractal

go run image3.go

Sql (sqlite) Golang example
maybe you also wanna take a look at my sql-examples-project

go run sqlite.go insert test
go run sqlite.go select

Public-key/asymmetric cryptography signing and validating

go run ppk-crypto.go

Command Line Arguments Golang Example We can get argument values though command line by specifying the operator '-' with the name of the argument and the value to be set. E.g. -env=qa

go run command_line_arguments.go
go run command_line_arguments.go -env=qa -consumer=true

Cron Golang Example We can trigger a function at a particular time through cron

go run cron.go

Map Golang Example Hash Map standard functions in golang

go run map.go

Compile

One great aspect of Golang is, that you can start go applications via go run name.go, but also compile it to an executable with go build name.go. After that you can start the compiled version which starts much faster. If you start fibonacci.go and the compiled version you will notice, that the last line which contains the execution time doesn't differ much, but if you start it with time ./fibonacci 32 and time go run ./fibonacci.go 32 you will see the difference.

License

Copyright © 2022 Simon Waldherr Dual-licensed. See the LICENSE file for details.

Support me

if you like what i do feel free to support me

you can do so by:

More Repositories

1

GoRealtimeWeb

Examples how to write realtime web applications in Golang
Go
220
star
2

micromarkdown.js

convert markdown to html in under 5kb
JavaScript
207
star
3

GolangSortingVisualization

examples of various sorting algorithms in golang (with visualization)
Go
122
star
4

golibs

general purpose Golang code (to be included in other projects)
Go
121
star
5

golang-benchmarks

Go(lang) benchmarks - (measure the speed of golang)
Go
116
star
6

passkit.php

a php function to create passes for Apple Passbook
PHP
61
star
7

PullToRefresh

a JavaScript implementation of PullToRefresh without jQuery or other Frameworks under MIT-License
HTML
57
star
8

HowTo-Deploy-LaTeX-Documents

Deploy LaTeX (and Markdown) Documents as PDF (and DjVu) via GitHub and TravisCI
TeX
49
star
9

ColorConverter.js

Convert between RGB, YUV, HSL, CMYK and HEX color defining with these JavaScript functions under MIT-License
HTML
45
star
10

zplgfa

#Golang package and cli tool for converting to #ZPL (from PNG, JPEG and GIF) for @ZebraTechnology-printers
Go
43
star
11

infinity.js

infinity.js adds infinite scrolling to webpages
JavaScript
43
star
12

cgolGo

Conway's Game of Life in Golang
Go
41
star
13

selfCSS

a CSS3 WYSIWYG Editor/Generator (in HTML5, CSS3 and JS)
JavaScript
35
star
14

disTime.js

converts UNIX-Timestamps to strings like " 5 days ago " in 19 languages
JavaScript
35
star
15

konami.js

logs every keypress and store it for later
JavaScript
34
star
16

parseTime.js

convert strings like "five days ago" to an integer (with time in seconds)
JavaScript
31
star
17

imgResize.js

smart resize images in a HTML5 Canvas
JavaScript
24
star
18

bbmandelbrotGo

generate images of a mandelbrot fractal
Go
20
star
19

wikiGo

mini wiki software in golang
Go
20
star
20

ups

Uncommon Printing System
Go
18
star
21

majaX.js

majaX stands for micro asynchronous javascript and X (X stands for XML, JSON, CSV, Plaintext, ...)
CoffeeScript
17
star
22

goCal

experimental #CalDAV + #WebCal Server in #Golang
Go
16
star
23

gwv

Golang Web Valve - to be connected to your series of tubes
Go
16
star
24

saprfc

call SAP ABAP Code from Golang (Remote Function Call)
Go
15
star
25

CSSfilter.js

CSSfilter.js helps you, adding CSS filters to images (or other elements)
JavaScript
14
star
26

fsagent

watch a folder for new or modified files and do something (copy, move, delete, send via mail, ...)
Go
13
star
27

golang-minigames

Go
12
star
28

cryptofoo

a good compromise between speed and validity to hash strings
JavaScript
10
star
29

sql-examples

sql examples (sqlite)
9
star
30

uploader

Multiple file upload plugin with progress-bar, drag-and-drop
JavaScript
7
star
31

ColorConverterGo

Convert between RGB, HSL and HEX color defining with these GO functions under MIT-License
Go
6
star
32

micromarkdown.php

https://github.com/SimonWaldherr/micromarkdown.js translated to php
PHP
6
star
33

se16jsonify

access SAP Database Tables and RFC-able Functions | example
Go
6
star
34

wp-osf-shownotes

simplifies Show Notes, write them in OSF, get them as HTML
CSS
6
star
35

DOMpteur

play with the Document Object Model (DOM) tree
JavaScript
5
star
36

micromarkdownGo

https://github.com/SimonWaldherr/micromarkdown.js translated to golang
Go
5
star
37

phpmd

convert md to html via php and regex
PHP
5
star
38

ScrapeEMS

ScrapeEMS is a #golang #cli tool to scrape the EMS (#ELDIS Management Suite)
Go
4
star
39

loginCtrl

a easy to use, free login system. (PHP, JS, SQLite/MySQL)
PHP
4
star
40

ircLogger.go

Go
4
star
41

rpi-examples

Raspberry Pi Golang Examples
Go
4
star
42

podlovejs

Podlove Web Player TNG – for internal bastelling only.
JavaScript
4
star
43

ColorConverter.php

Convert between RGB, HSL and HEX color defining with these PHP function under MIT-License
PHP
4
star
44

FormMate

FormMate is a Framework for making web forms
JavaScript
3
star
45

liveCalc

having fun with arithmetic
HTML
3
star
46

telnet2http.go

telnet server and http client in golang
Go
3
star
47

OTP-CAPTCHA

OneTimePad-Completely Automated Public Turing test to tell Computers and Humans Apart
PHP
3
star
48

Arduino-sketchbook

My Arduino sketches on GitHub
Arduino
3
star
49

Target3001-templates-and-examples

templates and examples for Target3001!
3
star
50

ranger

generates regexp code for numeric ranges
Go
3
star
51

canvastools.js

tools for a html5 canvas
JavaScript
3
star
52

colorize.js

converts integer to color
JavaScript
3
star
53

FluidSimASCII

This is a Golang fluid simulator using the "Smoothed-particle hydrodynamics (SPH)" method
Go
3
star
54

listDnD

sort lists via Drag and Drop. This is a fork from tool-man.org
JavaScript
3
star
55

easySQL

a database wrapper for easy read and write actions on a sql db (SQLite, MySQL, PostgreSQL, ...)
PHP
2
star
56

node.js-example

an example how to use node.js as a webserver
JavaScript
2
star
57

OSF.php

a repo for the main-code of the OSF parser (to include in other projects)
PHP
2
star
58

cgol.rs

Conway's Game of Life in Rust
Rust
2
star
59

BaF-Framework

HTML buttons and forms (since baf 2.0)
JavaScript
2
star
60

podlove-font

Shell
2
star
61

CocktailTDI

PHP
2
star
62

CalCalc.js

JavaScript functions to calculate calendars
HTML
2
star
63

FOJSLC

Free Open JavaScript Lib Collection
JavaScript
2
star
64

hx711go

Golang package to interface hx711 load cell amplifier
Go
2
star
65

tcial.js

the cake is a lie, but the cookie isn't
JavaScript
1
star
66

str2ascii

text to ascii and reverse
PHP
1
star
67

DSV

An easy to use collection of php functions to deal with DSV files. Convert DSV files to a 2D Array, RSS-Feed, Atom-Feed, .htaccess, .htpasswd, HTML, FEA, ...
PHP
1
star
68

GameOfLife

multiple implementations of Conway's Game of Life
Java
1
star
69

pico75player

play animated GIFs on a Hub75 Matrix with Raspberry Pi Pico (Pimoroni Interstate 75)
Go
1
star
70

DIY-Arcade-Machine

my very own arcade machine
Python
1
star
71

lightbox.js

a free, easy to use, tiny, jquery free lightbox script
JavaScript
1
star
72

go-wiki

mirror of the github golang wiki
1
star
73

Datanalyze

1
star
74

ScreenShare2040

Draw via browser, upload images and screen-share to a RGB-LED-Matrix
HTML
1
star
75

git-iso-29500

Dieses Dokument dient zur Eruierung der Praktikabilität von Git-Hooks zur Git-ifizierung von .docx-Dateien
Shell
1
star
76

SimonWaldherr

1
star
77

movingavg

In statistics, a moving average is a calculation to analyze data points by creating a series of averages of different subsets of the full data set. #golang
Go
1
star
78

mySlid.es

a impress.js editor
PHP
1
star
79

BookTemplate

automate your document generation process
Nix
1
star
80

podlove-templates

Templates for the Podlove Publisher
HTML
1
star
81

data-href

ajax for normal links
JavaScript
1
star
82

sapUserManager

SAP User Copy via BAPIs
Go
1
star
83

rp2040-examples

Examples for Raspberry Pi Pico (RP2040 MCU based SBCs)
Python
1
star
84

ColorConverter.swift

Swift
1
star
85

dotfiles

my dotfiles
Shell
1
star
86

tableCtrl

make, modify, manage, export and delete HTML tables
JavaScript
1
star
87

Die-Gedanken-sind-frei

Hier nutze ich Git/GitHub als eine art Blog. Dies ist kein Software Repo! Alle Artikel sind, wie der Titel vermuten lässt, unter einer freien Lizenz, erhältlich (cc-by-sa)! Most of the content is in german, but sometimes in english!
1
star