Home

Creating and Testing a Simple HTTP Server in Go Programming

36 views

Creating a simple HTTP server in Go is straightforward using the net/http package. Below is a basic example that shows how to set up an HTTP server that listens on a specified port and handles requests.

Example: Simple HTTP Server in Go

  1. Install Go (if you haven't already) by following the instructions on the official Go website.

  2. Create a new Go file (main.go) and add the following code:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Handle the root path
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, World!")
	})

	// Handle the /hello path
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
	})

	// Start the server on port 8080
	fmt.Println("Server is listening on port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Failed to start server:", err)
	}
}

Explanation:

  1. Import Required Packages:

    • fmt: For formatting strings and printing to the console.
    • net/http: For creating the HTTP server and handling HTTP requests.
  2. Define Handlers:

    • http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request)): This sets up a handler for the root URL path ("/"). When this path is accessed, it writes "Hello, World!" to the response.
    • http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request)): This sets up a handler for the /hello path. It extracts a query parameter named name from the URL and responds with "Hello, [name]!".
  3. Start the Server:

    • http.ListenAndServe(":8080", nil): This starts the HTTP server on port 8080. It blocks the main thread and listens for incoming HTTP requests. If there's an error starting the server, it prints an error message.

Running the Server:

To run the server, use the go run command:

go run main.go

You should see the message "Server is listening on port 8080" in your terminal.

Testing the Server:

  • Open your web browser and navigate to http://localhost:8080. You should see the message "Hello, World!".

  • Navigate to http://localhost:8080/hello?name=Go. You should see the message "Hello, Go!".

This example demonstrates how to set up a simple HTTP server in Go with basic routing. For more advanced features, you could look into middleware, template rendering, and third-party libraries like gorilla/mux for more complex routing needs.