158x Filetype PDF File size 0.07 MB Source: cdn.comparitech.com
Cheat Sheet Series Network Programming with Go Operators Comments Functions TCP Socket programming Attribution: Arithmetic operators // Line comments func function_name( [parameter list] ) [return_types] 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 { -client /* General comments - closed */ 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 break • default • func • interface • select • case • defer • go • map • struct • chan • AWS Lambda Function Handler in Go package main % remainder integers 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 import ( "fmt" Controls &^ bit clear (AND NOT) integers "fmt" "net" if x > 0 { "github.com/aws/aws-lambda-go/lambda" "os" << left shift integer << unsigned integer 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() { Age int 'json:"How old are you?"' arguments := os.Args != not equal // 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:"' } Loop } >= greater or equal } for i < 10 { // omit semicolons if there is only a condition CONNECT := arguments[1] Logical operators } 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 { } default: s3() Variables 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 AWS S3 Bucket List fmt.Fprintf(c, text+"\n") Arrays • Slices • Ranges var k = 0 package main var x, y float32 = -1, -2 [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" "github.com/aws/aws-sdk-go/service/s3" } make([]T, length, capacity) uint8 the set of all unsigned 8-bit integers (0 to 255) ) } Slices // the following two expressions are equivalent Create the TCP Server the set of all unsigned 16-bit integers (0 to 65535) func main() { uint16 make([]int, 50, 100) //create a file named tcpS.go s3svc := s3.New(session.New()) new([100]int)[0:50] result, err := s3svc.ListBuckets(&s3.ListBucketsInput{}) uint32 the set of all unsigned 32-bit integers (0 to 4294967295) package main if err != nil { // RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] fmt.Println("Buckets list failed", err) uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) "range" Expression . 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 // type of i is int the set of all signed 16-bit integers (-32768 to 32767) "os" for _, bucket := range result.Buckets { // type of s is string "strings" fmt.Printf("%s : %s\n", aws.StringValue(bucket.Name), // s == a[i] int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) "time" bucket.CreationDate) g(i, s) ) } } the set of all signed 64-bit integers (-9223372036854775808 to } int64 9223372036854775807) func main() { arguments := os.Args Test the TCP Client and Server float32 the set of all IEEE-754 32-bit floating-point numbers 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 //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) the set of all complex numbers with float64 real and imaginary parts if err != nil { go run tcpC.go 127.0.0.1:1234 fmt.Println(err) byte alias for uint8 return //Note: If the TCP server is not running on the expected TCP port, you will get the following error message from tcpC.go: } rune alias for int32 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 } //You should see a similar output: //ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } for { ")" ) . >> Hello! netData, err := bufio.NewReader(c).ReadString('\n') //ImportSpec = [ "." | PackageName ] ImportPath . ->: 2019-05-23T19:43:21+03:00 if err != nil { //ImportPath = string_lit . fmt.Println(err) //Send the STOP command to exit the TCP client and server: return package main - // Package declaration } STOP if strings.TrimSpace(string(netData)) == "STOP" { // Multiple import statements fmt.Println("Exiting TCP server!") Import import "fmt" //You should see a similar output in the client: return import "time" declarations } import "math" >> STOP ->: TCP client exiting... fmt.Print("-> ", string(netData)) // Factored import statements t := time.Now() import ( //The output on the TCP server side will resemble the following: myTime := t.Format(time.RFC3339) + "\n" "fmt" c.Write([]byte(myTime)) "time" -> Hello! } "math" Exiting TCP server! } )
no reviews yet
Please Login to review.