Creating and Testing a Simple HTTP Server in Go Programming
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
-
Install Go (if you haven't already) by following the instructions on the official Go website.
-
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:
-
Import Required Packages:
fmt: For formatting strings and printing to the console.net/http: For creating the HTTP server and handling HTTP requests.
-
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/hellopath. It extracts a query parameter namednamefrom the URL and responds with "Hello, [name]!".
-
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.