Basic Go Code Example: Simple HTTP Server #
This example demonstrates a basic HTTP server written in Go. The server listens on a specified port and responds with a simple message when accessed.
Code #
// Package main defines the entry point of the application.
package main
import (
"fmt" // For formatted I/O
"net/http" // For creating an HTTP server
)
// handler function processes incoming HTTP requests.
func handler(w http.ResponseWriter, r *http.Request) {
// Send a response back to the client.
fmt.Fprintf(w, "Hello, World! You've requested: %s\n", r.URL.Path)
}
// main function is the entry point of the application.
func main() {
// Register the handler function for the root URL path ("/").
http.HandleFunc("/", handler)
// Start the HTTP server on port 8080.
fmt.Println("Server is listening on http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
// Log any error if the server fails to start.
fmt.Println("Error starting server:", err)
}
}
Explanation #
1. Import Statements #
fmt: Provides functions for formatted I/O, such as printing to the console or formatting text for HTTP responses.net/http: Contains functions and types for building HTTP servers and making HTTP requests.
2. The handler Function
#
- This is where the server processes incoming HTTP requests.
- The parameters are:
w http.ResponseWriter: Used to send a response back to the client.r *http.Request: Represents the client’s HTTP request.
- The
fmt.Fprintffunction sends a response message to the client, including the requested URL path.
3. The main Function
#
- Registers the
handlerfunction with the root URL path ("/"). - Calls
http.ListenAndServeto start the server:- The first argument specifies the port (
:8080). - The second argument is
nil, which means theDefaultServeMuxis used.
- The first argument specifies the port (
4. Running the Server #
- Save the code in a file named
main.go. - Open a terminal and navigate to the file’s directory.
- Run the following command to start the server:
go run main.go - Open your browser and go to
http://localhost:8080. You should see:Hello, World! You've requested: /
Key Concepts #
- Go’s
net/httpPackage: Provides everything needed for creating robust HTTP servers. - Handler Functions: Functions that process incoming HTTP requests and generate responses.
ListenAndServe: Starts the HTTP server and blocks until the program is terminated.