All the tables provided in the cheat sheets are also presented in tables below which are easy to copy and paste.
The Go Network Programming Cheat Sheet covers:
- Operators
- Variables
- Packages
- Comments
- Reserved Keywords
- Controls
- Arrays, Slices, & Ranges
- Functions
- TCP Socket Programming with Go
- Creating a TCP client with Go
- Creating a TCP Server with Go
- Testing the TCP Client and Server with Go
- AWS Lambda Function Handler example with Go
- AWS Bucket List example with Go
View or Download the Cheat Sheet JPG image
Right-click on the image below to save the JPG file (2500 width x 1981 height in pixels), or click here to open it in a new browser tab. Once the image opens in a new window, you may need to click on the image to zoom in and view the full-sized JPG.
View or Download the cheat sheet PDF file
Download the cheat sheet PDF file here. When it opens in a new browser tab, simply right click on the PDF and navigate to the download menu.
What’s included in this cheat sheet
The following categories and items have been included in the cheat sheet:
Operators
Arithmetic operators |
||
+ | sum | integers, floats, complex values, strings |
- | difference | integers, floats, complex values |
* | product | integers, floats, complex values |
/ | quotient | integers, floats, complex values |
% | remainder | integers |
& | bitwise AND | integers |
| | bitwise OR | integers |
^ | bitwise XOR | integers |
&^ | bit clear (AND NOT) | integers |
<< | left shift | integer << unsigned integer |
>> | right shift | integer >> unsigned integer |
Comparison operators |
||
== | equal | |
!= | not equal | |
< | less | |
<= | less or equal | |
> | greater | |
>= | greater or equal | |
Logical operators |
||
&& | conditional AND | p && q is "if p then q else false" |
|| | conditional OR | p || q is "if p then true else q" |
! | NOT | !p is "not p" |
Variables
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) |
|
var i int |
|
uint8 | the set of all unsigned 8-bit integers (0 to 255) |
uint16 | the set of all unsigned 16-bit integers (0 to 65535) |
uint32 | the set of all unsigned 32-bit integers (0 to 4294967295) |
uint64 | the set of all unsigned 64-bit integers (0 to 18446744073709551615) |
int8 | the set of all signed 8-bit integers (-128 to 127) |
int16 | the set of all signed 16-bit integers (-32768 to 32767) |
int32 | the set of all signed 32-bit integers (-2147483648 to 2147483647) |
int64 | the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) |
float32 | the set of all IEEE-754 32-bit floating-point numbers |
float64 | the set of all IEEE-754 64-bit floating-point numbers |
complex64 | the set of all complex numbers with float32 real and imaginary parts |
complex128 | the set of all complex numbers with float64 real and imaginary parts |
byte | alias for uint8 |
Packages
Clause | // PackageClause = "package" PackageName |
Import declarations | //ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) |
Comments
// Line comments |
|
/* General comments - closed */ |
Reserved Keywords
break • default • func • interface • select • case • defer • go • map • struct • chan • else • goto • package • switch • const • fallthrough • if • range • type • continue • for • import • return • var |
Controls
If, Else | if x > 0 { |
Loop | // Only `for`, no `while`, no `until` |
Switch | switch tag { |
Arrays, Slices, & Ranges
Arrays | [32]byte |
Slices | make([]T, length, capacity) |
Ranges | // RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression . |
Functions
Structure | func function_name( [parameter list] ) [return_types] |
TCP Socket Programming with Go
Creating a TCP client with Go
//create a file named tcpC.go
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide host:port.")
return
}
CONNECT := arguments[1]
c, err := net.Dial("tcp", CONNECT)
if err != nil {
fmt.Println(err)
return
}
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print(">> ")
text, _ := reader.ReadString('\n')
fmt.Fprintf(c, text+"\n")
message, _ := bufio.NewReader(c).ReadString('\n')
fmt.Print("->: " + message)
if strings.TrimSpace(string(text)) == "STOP" {
fmt.Println("TCP client exiting...")
return
}
}
}
Creating a TCP Server with Go
//create a file named tcpS.go
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
"time"
)
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide port number")
return
}
PORT := ":" + arguments[1]
l, err := net.Listen("tcp", PORT)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
for {
netData, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
if strings.TrimSpace(string(netData)) == "STOP" {
fmt.Println("Exiting TCP server!")
return
}
fmt.Print("-> ", string(netData))
t := time.Now()
myTime := t.Format(time.RFC3339) + "\n"
c.Write([]byte(myTime))
}
}
Testing the TCP Client and Server with Go
//Run your TCP server. From the directory containing the tcpS.go file, run the following command: go run tcpS.go 1234 //The server will listen on port number 1234. You will not see any output as a result of this command. //Open a second shell session to execute the TCP client and to interact with the TCP server. Run the following command: go run tcpC.go 127.0.0.1:1234 //Note: If the TCP server is not running on the expected TCP port, you will get the following error message from tcpC.go: dial tcp [::1]:1234: connect: connection refused //You will see a >> prompt waiting for you to enter some text. Type in Hello! to receive a response from the TCP server: Hello! //You should see a similar output: >> Hello! ->: 2019-05-23T19:43:21+03:00 //Send the STOP command to exit the TCP client and server: STOP //You should see a similar output in the client: >> STOP ->: TCP client exiting... //The output on the TCP server side will resemble the following: -> Hello! Exiting TCP server!
AWS Lambda Function Handler example with Go
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string 'json:"What is your name?"'
Age int 'json:"How old are you?"'
}
type MyResponse struct {
Message string 'json:"Answer:"'
}
func HandleLambdaEvent(event MyEvent) (MyResponse, error) {
return MyResponse{Message: fmt.Sprintf("%s is %d years old!", event.Name,\event.Age)}, nil
}
func main() {
lambda.Start(HandleLambdaEvent)
}
AWS Bucket List example with Go
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
func main() {
s3svc := s3.New(session.New())
result, err := s3svc.ListBuckets(&s3.ListBucketsInput{})
if err != nil {
fmt.Println("Buckets list failed", err)
return
}
fmt.Println("Buckets:")
for _, bucket := range result.Buckets {
fmt.Printf("%s : %s\n", aws.StringValue(bucket.Name), bucket.CreationDate)
}
}
Reference and further reading
- TCP Socket programming – Code Attribution: https://www.linode.com/docs/development/go/developing-udp-and-tcp-clients-and-servers-in-go/#create-the-tcp-client
- AWS Lambda Function Handler in Go – Based on AWS docs: https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html
- GoLang Reference Website: golang.org
Go network programming FAQs
Is go good for network programming?
Go includes function libraries for network-related tasks. The language is a compiled system, unlike Web-programming languages, such as Python and JavaScript. One reason that this language is good for network programming is it includes routines to spawn and monitor new threads, which is ideal for creating daemons and maintaining connection sessions. Kubernetes and Docker are written in Go.
What is the Go Programming language used for?
Go was created by Google as a replacement for C++, which is an object-oriented version of the C programming language. Go is a compiled system, which makes it faster to execute because it doesn’t need a runtime interpreter like script-based languages, such as JavaScript and Python. Once compiled, Go programs are good at managing memory and creating multi-threaded execution. These features make the language great for running background processes and managing network data exchanges.
What is meant by network programming?
Network programming involves managing connections and data exchanges across a network. This can involve issues such as protocol management for TCP or orchestration between software packages across a network, which includes buffering data in memory for transmission and verifying received data.