Skip to main content
  1. Posts/

Go Code Example

·2 mins· loading · loading · ·
Table of Contents

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.Fprintf function sends a response message to the client, including the requested URL path.

3. The main Function
#

  • Registers the handler function with the root URL path ("/").
  • Calls http.ListenAndServe to start the server:
    • The first argument specifies the port (:8080).
    • The second argument is nil, which means the DefaultServeMux is used.

4. Running the Server
#

  1. Save the code in a file named main.go.
  2. Open a terminal and navigate to the file’s directory.
  3. Run the following command to start the server:
    go run main.go
    
  4. Open your browser and go to http://localhost:8080. You should see:
    Hello, World! You've requested: /
    

Key Concepts
#

  • Go’s net/http Package: 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.