Go Static File Serving 🎯

beginner
6 min

Go Static File Serving 🎯

Welcome to our lesson on Go static file serving! This tutorial is designed to help you understand how to serve static files using Go, a powerful and efficient programming language. By the end of this lesson, you'll be able to create a simple web server that serves static files like HTML, CSS, and JavaScript.

What is Go? 📝

Go, also known as Golang, is an open-source programming language developed by Google. It's known for its simplicity, efficiency, and strong support for concurrent programming.

Why Use Go for Static File Serving? 💡

Go is a great choice for serving static files because it's fast, lightweight, and easy to use. It allows you to create a web server quickly and efficiently, making it perfect for projects that require serving static files.

Setting Up Your Environment ✅

Before we dive into the code, let's make sure you have Go installed on your machine. You can download it from here. After installing, verify the installation by running go version in your terminal.

Creating a Web Server 🎨

Now, let's create a simple web server using Go. In this example, we'll serve an index.html file from the current directory.

go
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome to our simple web server!") }) http.HandleFunc("/index.html", func(w http.ResponseWriter, r *http.Request) { // Open the file and serve its content data, err := fs.ReadFile("index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write(data) }) // Start the server on port 8080 err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } }

This code creates a web server that listens on port 8080. When a client requests the root ("/") or /index.html path, it responds with a custom message or serves the index.html file, respectively.

Running the Server 🔄

Save this code in a file named main.go and run it using the following command:

bash
go run main.go

Now, open your browser and navigate to http://localhost:8080. You should see the message from the root handler. To test the index.html handler, create an index.html file with the following content:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First Web Page</title> </head> <body> <h1>Welcome to my web page!</h1> </body> </html>

Save this file in the same directory as main.go and refresh your browser. You should now see the content of the index.html file.

Next Steps 💡

Now that you've learned how to serve static files using Go, you can explore more advanced topics like handling dynamic content, routing, and working with templates. Happy coding!

Quick Quiz
Question 1 of 1

What is the purpose of the `http.HandleFunc` function in the Go code?