Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
86 views

Network Programming With Go Cheat Sheet

This document provides a cheat sheet on network programming with Go, including common operators, comments, functions, TCP socket programming, and AWS Lambda function handlers in Go. It lists arithmetic, comparison, and logical operators. It also covers line comments, multi-line comments, keywords, functions, and control structures like if/else statements and for loops. It provides an example of creating a TCP client in Go and the structure of an AWS Lambda function handler.

Uploaded by

Thành Phúc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Network Programming With Go Cheat Sheet

This document provides a cheat sheet on network programming with Go, including common operators, comments, functions, TCP socket programming, and AWS Lambda function handlers in Go. It lists arithmetic, comparison, and logical operators. It also covers line comments, multi-line comments, keywords, functions, and control structures like if/else statements and for loops. It provides an example of creating a TCP client in Go and the structure of an AWS Lambda function handler.

Uploaded by

Thành Phúc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Network Programming with Go Cheat Sheet Series

Operators Comments Functions TCP Socket programming


Arithmetic operators // Line comments func function_name( [parameter list] ) [return_types]
Attribution:
https://www.linode.com/docs/development/go/developing-udp-and-tcp-clients-and-servers-in-go/#create-the-tcp
+ sum integers, floats, complex values, strings /* General comments - closed */ { -client
Structure Function body
- difference integers, floats, complex values Create the TCP Client
}
* product integers, floats, complex values Reserved Keywords //create a file named tcpC.go
/ quotient integers, floats, complex values
% remainder integers
break • default • func • interface • select • case • defer • go • map • struct • chan • AWS Lambda Function Handler in Go package main
else • goto • package • switch • const • fallthrough • if • range • type • continue • Based on AWS docs: https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html
& bitwise AND integers
for • import • return • var package main import (
| bitwise OR integers
"bufio"
^ bitwise XOR integers
Controls import ( "fmt"
&^ bit clear (AND NOT) integers "fmt" "net"
<< left shift integer << unsigned integer if x > 0 { "github.com/aws/aws-lambda-go/lambda" "os"
return x ) "strings"
>> right shift integer >> unsigned integer
If, Else } else { )
Comparison operators return -x type MyEvent struct {
== equal } Name string 'json:"What is your name?"' func main() {
!= not equal Age int 'json:"How old are you?"' arguments := os.Args
// Only `for`, no `while`, no `until` } if len(arguments) == 1 {
< less
for i := 1; i < 10; i++ { fmt.Println("Please provide host:port.")
<= less or equal } type MyResponse struct { return
> greater for ; i < 10; { // while - loop Message string 'json:"Answer:"' }
>= greater or equal Loop } }
for i < 10 { // omit semicolons if there is only a condition
Logical operators CONNECT := arguments[1]
} func HandleLambdaEvent(event MyEvent) (MyResponse, error) { c, err := net.Dial("tcp", CONNECT)
&& conditional AND p && q is "if p then q else false" for { // you can omit the condition ~ while (true) return MyResponse{Message: fmt.Sprintf("%s is %d years old!", event.Name,\ if err != nil {
|| conditional OR p || q is "if p then true else q" } event.Age)}, nil fmt.Println(err)
! NOT !p is "not p" } return
switch tag { }
Variables default: s3() func main() {
Switch case 0, 1, 2, 3: s1() lambda.Start(HandleLambdaEvent) for {
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
case 4, 5, 6, 7: s2() } reader := bufio.NewReader(os.Stdin)
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
} fmt.Print(">> ")
var i int
text, _ := reader.ReadString('\n')
var U, V, W float64
Arrays • Slices • Ranges AWS S3 Bucket List fmt.Fprintf(c, text+"\n")
var k = 0
var x, y float32 = -1, -2 package main
[32]byte message, _ := bufio.NewReader(c).ReadString('\n')
var (
[2*N] struct { x, y int32 } import ( fmt.Print("->: " + message)
i int
Arrays [1000]*float64 "fmt" if strings.TrimSpace(string(text)) == "STOP" {
u, v, s = 2.0, 3.0, "bar"
[3][5]int fmt.Println("TCP client exiting...")
)
[2][2][2]float64 // same as [2]([2]([2]float64)) "github.com/aws/aws-sdk-go/aws" return
var re, im = complexSqrt(-1)
"github.com/aws/aws-sdk-go/aws/session" }
var _, found = entries[name] // map lookup; only interested in "found"
make([]T, length, capacity) "github.com/aws/aws-sdk-go/service/s3" }
uint8 the set of all unsigned 8-bit integers (0 to 255) ) }
Slices // the following two expressions are equivalent Create the TCP Server
uint16 the set of all unsigned 16-bit integers (0 to 65535) make([]int, 50, 100) func main() {
//create a file named tcpS.go
new([100]int)[0:50] s3svc := s3.New(session.New())
uint32 the set of all unsigned 32-bit integers (0 to 4294967295) result, err := s3svc.ListBuckets(&s3.ListBucketsInput{})
package main
// RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] if err != nil {
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) "range" Expression . fmt.Println("Buckets list failed", err)
import (
return
"bufio"
int8 the set of all signed 8-bit integers (-128 to 127) var a [10]string }
"fmt"
for i, s := range a { "net"
Ranges fmt.Println("Buckets:")
int16 the set of all signed 16-bit integers (-32768 to 32767) // type of i is int "os"
// type of s is string for _, bucket := range result.Buckets {
"strings"
fmt.Printf("%s : %s\n", aws.StringValue(bucket.Name),
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) // s == a[i] "time"
g(i, s) bucket.CreationDate)
)
} }
the set of all signed 64-bit integers (-9223372036854775808 to
int64 9223372036854775807) }
func main() {
arguments := os.Args
float32 the set of all IEEE-754 32-bit floating-point numbers Test the TCP Client and Server if len(arguments) == 1 {
//Run your TCP server. From the directory containing the tcpS.go file, run the following command: fmt.Println("Please provide port number")
float64 the set of all IEEE-754 64-bit floating-point numbers return
go run tcpS.go 1234 }
complex64 the set of all complex numbers with float32 real and imaginary parts
//The server will listen on port number 1234. You will not see any output as a result of this command. PORT := ":" + arguments[1]
complex128 the set of all complex numbers with float64 real and imaginary parts //Open a second shell session to execute the TCP client and to interact with the TCP server. Run the following command: l, err := net.Listen("tcp", PORT)
if err != nil {
byte alias for uint8 go run tcpC.go 127.0.0.1:1234 fmt.Println(err)
return
rune alias for int32 //Note: If the TCP server is not running on the expected TCP port, you will get the following error message from tcpC.go: }
defer l.Close()
dial tcp [::1]:1234: connect: connection refused
Packages c, err := l.Accept()
// PackageClause = "package" PackageName . //You will see a >> prompt waiting for you to enter some text. Type in Hello! to receive a response from the TCP server: if err != nil {
// PackageName = identifier . fmt.Println(err)
Clause
Hello! return
package math }
//ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } //You should see a similar output:
")" ) . for {
//ImportSpec = [ "." | PackageName ] ImportPath . >> Hello! netData, err := bufio.NewReader(c).ReadString('\n')
//ImportPath = string_lit . ->: 2019-05-23T19:43:21+03:00 if err != nil {
fmt.Println(err)
package main - // Package declaration //Send the STOP command to exit the TCP client and server: return
}
// Multiple import statements STOP if strings.TrimSpace(string(netData)) == "STOP" {
Import import "fmt" fmt.Println("Exiting TCP server!")
declarations import "time" //You should see a similar output in the client: return
import "math" }
>> STOP
// Factored import statements ->: TCP client exiting... fmt.Print("-> ", string(netData))
import ( t := time.Now()
"fmt" //The output on the TCP server side will resemble the following: myTime := t.Format(time.RFC3339) + "\n"
"time" c.Write([]byte(myTime))
"math" -> Hello! }
) Exiting TCP server! }

You might also like