Practical Go Coding Samples
In this section, we'll explore some practical Go coding samples that demonstrate the language's capabilities and versatility.
Web Server Example
Let's start with a simple web server example. This code creates a basic HTTP server that listens on port 8080 and responds with "Hello, World!" when a client makes a request.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
fmt.Println("Starting server on port 8080")
http.ListenAndServe(":8080", nil)
}
To run this example, save the code in a file (e.g., main.go
) and execute the following command in your terminal:
go run main.go
You can then open a web browser and visit ` to see the "Hello, World!" response.
File I/O Example
Next, let's look at an example of reading and writing files in Go.
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
// Write to a file
err := ioutil.WriteFile("example.txt", []byte("Hello, file!"), 0644)
if err != nil {
fmt.Println("Error writing file:", err)
return
}
fmt.Println("File written successfully")
// Read from a file
data, err := ioutil.ReadFile("example.txt")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println("File content:", string(data))
}
In this example, we first write the string "Hello, file!" to a file named example.txt
. Then, we read the contents of the file and print them to the console.
Goroutines and Channels Example
Go's concurrency primitives, goroutines and channels, allow you to write highly concurrent and scalable programs. Here's an example that demonstrates their usage:
package main
import (
"fmt"
"time"
)
func main() {
// Create a channel to communicate between goroutines
messages := make(chan string)
// Start a goroutine to send a message
go func() {
time.Sleep(2 * time.Second)
messages <- "hello"
}()
// Receive the message from the channel
msg := <-messages
fmt.Println(msg)
}
In this example, we create a channel to communicate between two goroutines. One goroutine sends the message "hello" to the channel after a 2-second delay, and the other goroutine receives the message and prints it to the console.
These examples should give you a good starting point for exploring practical Go coding samples. As you progress, you can build upon these basics to create more complex and sophisticated applications.