Go > Web Development > HTTP Basics > Creating HTTP servers
Basic HTTP Server
This snippet demonstrates how to create a simple HTTP server in Go that listens on a specified port and responds with a 'Hello, World!' message. It's a fundamental building block for web applications.
Code Snippet
This code defines a basic HTTP server. It imports the necessary packages (`fmt`, `net/http`, `log`). The `handler` function is the core logic, writing 'Hello, World!' to the HTTP response. `http.HandleFunc` registers the handler function for the root path ('/'). `http.ListenAndServe` starts the server, listening on port 8080. The `log.Fatal` ensures the program exits if the server fails to start.
package main
import (
"fmt"
"net/http"
"log"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server starting on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Concepts Behind the Snippet
This snippet relies on the concept of request handlers. An HTTP server receives requests and dispatches them to registered handlers. The `net/http` package provides the tools for creating servers and handling requests. The `ResponseWriter` is where you write the response data, and the `Request` contains information about the incoming request (headers, method, URL, etc.).
Real-Life Use Case
This basic server can be the starting point for any web application. You can expand the `handler` function to handle different routes, read request data (like form submissions), interact with databases, and generate dynamic HTML.
Best Practices
Interview Tip
Be prepared to explain the role of each function (`HandleFunc`, `ListenAndServe`, `ResponseWriter`, `Request`). Also, understand the difference between using `log.Fatal` vs. more sophisticated error handling techniques.
When to Use Them
Use this basic server structure when you need to quickly prototype a web application or create a simple API endpoint. It's also useful for learning the fundamentals of HTTP servers in Go.
Alternatives
Pros
Cons
FAQ
-
What does `http.HandleFunc` do?
It registers a handler function for a specific path. In this case, it registers the `handler` function for the root path ('/'). When the server receives a request for '/', it will call the `handler` function. -
What is the purpose of `ResponseWriter`?
The `ResponseWriter` interface is used to construct the HTTP response that the server sends back to the client. You can use it to set headers, write the response body, and set the HTTP status code. -
Why use `log.Fatal`?
`log.Fatal` logs an error message and then calls `os.Exit(1)`, which terminates the program. In this simple example, it ensures that the program exits if the server fails to start. In a production environment, a more sophisticated error handling strategy might be preferred.