# Go

<figure><img src="/files/dzqg1nbpUopCKbpsPbl0" alt="" width="111"><figcaption></figcaption></figure>

Go (or Golang) is an open-source programming language designed for efficiency and scalability. Its simplicity and strong performance make it ideal for security tasks, including scripting and penetration testing.

### Setting Up the Go Environment

1. **Install Go:**
   * Download from the [official website](https://golang.org/dl/).
   * Follow installation instructions for your operating system.
2. **Verify Installation:**

   ```sh
   go version
   ```
3. **Setting Up GOPATH:**

   * GOPATH is the workspace for Go projects.

   ```sh
   export GOPATH=$HOME/go
   export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
   ```

### Basic Syntax

1. **Hello World:**

   ```go
   package main

   import "fmt"

   func main() {
       fmt.Println("Hello, World!")
   }
   ```
2. **Variables:**

   ```go
   var a string = "Initial"
   b := 2 // Short variable declaration
   ```
3. **Loops:**

   ```go
   goCopy codefor i := 0; i < 10; i++ {
       fmt.Println(i)
   }
   ```
4. **Conditional Statements:**

   ```go
   if x > 10 {
       fmt.Println("x is greater than 10")
   } else {
       fmt.Println("x is less than or equal to 10")
   }
   ```

### Handling HTTP Requests

1. **GET Request:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
       "net/http"
   )

   func main() {
       resp, err := http.Get("http://example.com")
       if err != nil {
           fmt.Println(err)
           return
       }
       defer resp.Body.Close()
       body, err := ioutil.ReadAll(resp.Body)
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(string(body))
   }
   ```
2. **POST Request:**

   ```go
   package main

   import (
       "bytes"
       "fmt"
       "net/http"
   )

   func main() {
       jsonData := []byte(`{"key":"value"}`)
       resp, err := http.Post("http://example.com", "application/json", bytes.NewBuffer(jsonData))
       if err != nil {
           fmt.Println(err)
           return
       }
       defer resp.Body.Close()
       fmt.Println("Response Status:", resp.Status)
   }
   ```

### &#x20;Parsing JSON

1. **Parsing JSON Response:**

   ```go
   package main

   import (
       "encoding/json"
       "fmt"
   )

   type Response struct {
       Key string `json:"key"`
   }

   func main() {
       jsonStr := `{"key": "value"}`
       var res Response
       json.Unmarshal([]byte(jsonStr), &res)
       fmt.Println(res.Key)
   }
   ```
2. **Encoding JSON:**

   ```go
   package main

   import (
       "encoding/json"
       "fmt"
   )

   type Payload struct {
       Key string `json:"key"`
   }

   func main() {
       data := Payload{Key: "value"}
       jsonData, _ := json.Marshal(data)
       fmt.Println(string(jsonData))
   }
   ```

### Concurrency in Go

1. **Goroutines:**

   ```go
   package main

   import (
       "fmt"
       "time"
   )

   func main() {
       go func() {
           fmt.Println("Hello from Goroutine")
       }()
       time.Sleep(time.Second) // Wait for Goroutine to finish
   }
   ```
2. **Channels:**

   ```go
   package main

   import "fmt"

   func main() {
       messages := make(chan string)

       go func() {
           messages <- "ping"
       }()

       msg := <-messages
       fmt.Println(msg)
   }
   ```

### Writing Secure Code

1. **Input Validation:**
   * Always validate user input to avoid injection attacks.
2. **Using Context for Timeouts:**

   ```go
   package main

   import (
       "context"
       "fmt"
       "net/http"
       "time"
   )

   func main() {
       ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
       defer cancel()

       req, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)
       resp, err := http.DefaultClient.Do(req)
       if err != nil {
           fmt.Println("Request failed:", err)
           return
       }
       defer resp.Body.Close()
       fmt.Println("Response Status:", resp.Status)
   }
   ```

### File Handling

1. **Reading Files:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
   )

   func main() {
       content, err := ioutil.ReadFile("file.txt")
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(string(content))
   }
   ```
2. **Writing Files:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
   )

   func main() {
       content := []byte("Hello, World!")
       err := ioutil.WriteFile("file.txt", content, 0644)
       if err != nil {
           fmt.Println(err)
       }
   }
   ```

### Networking

1. **Simple TCP Client:**

   ```go
   package main

   import (
       "bufio"
       "fmt"
       "net"
   )

   func main() {
       conn, err := net.Dial("tcp", "example.com:80")
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
       status, err := bufio.NewReader(conn).ReadString('\n')
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(status)
   }
   ```
2. **Simple TCP Server:**

   ```go
   package main

   import (
       "fmt"
       "net"
   )

   func main() {
       ln, err := net.Listen("tcp", ":8080")
       if err != nil {
           fmt.Println(err)
           return
       }
       for {
           conn, err := ln.Accept()
           if err != nil {
               fmt.Println(err)
               continue
           }
           go handleConnection(conn)
       }
   }

   func handleConnection(conn net.Conn) {
       fmt.Fprintln(conn, "Hello, World!")
       conn.Close()
   }
   ```

### Using Go for Penetration Testing

1. **Port Scanner:**

   ```go
   package main

   import (
       "fmt"
       "net"
       "time"
   )

   func main() {
       for i := 1; i <= 1024; i++ {
           address := fmt.Sprintf("scanme.nmap.org:%d", i)
           conn, err := net.DialTimeout("tcp", address, time.Second)
           if err != nil {
               continue
           }
           conn.Close()
           fmt.Printf("Port %d is open\n", i)
       }
   }
   ```
2. **HTTP Basic Authentication Brute Force:**

   ```go
   package main

   import (
       "fmt"
       "net/http"
       "strings"
   )

   func main() {
       url := "http://example.com"
       username := "admin"
       passwords := []string{"password1", "password2", "password3"}

       for _, password := range passwords {
           client := &http.Client{}
           req, _ := http.NewRequest("GET", url, nil)
           req.SetBasicAuth(username, password)
           resp, err := client.Do(req)
           if err != nil {
               fmt.Println("Request failed:", err)
               continue
           }
           if resp.StatusCode == 200 {
               fmt.Printf("Found valid credentials: %s:%s\n", username, password)
               break
           }
       }
   }
   ```

### Libraries and Tools

1. **Gorilla Web Toolkit:**
   * Useful for building robust web applications.
   * [Gorilla Toolkit](https://www.gorillatoolkit.org/)
2. **GoPacket:**
   * Library for packet processing with Go.
   * [GoPacket](https://github.com/google/gopacket)
3. **Zerolog:**
   * Fast and efficient structured logging library.
   * [Zerolog](https://github.com/rs/zerolog)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hackerspot.net/cheatsheets/coding/go.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
