Simple HTTP Server Examples in Go
Introduction
Creating a simple HTTP server in Go is an excellent way to grasp the basics of web development with this powerful language. In this article, we will go through three diverse examples that illustrate the process of setting up a simple HTTP server. Each example will showcase different functionalities, helping you understand how to build and customize your server for various use cases.
Example 1: Basic HTTP Server
Context
This example demonstrates how to set up a basic HTTP server that responds with a simple message. It’s perfect for beginners looking to understand the fundamentals of HTTP handling in Go.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Starting server at :8080")
http.ListenAndServe(":8080", nil)
}
Notes
- In this example, we define a function
handlerthat writes “Hello, World!” to the response writer. Thehttp.HandleFuncfunction maps the root URL (/) to this handler. - You can run this server by executing the code and then visiting
http://localhost:8080in your web browser.
Example 2: JSON Response Server
Context
In this example, we will create an HTTP server that responds with a JSON object. This is useful when building APIs or services that need to send structured data.
package main
import (
"encoding/json"
"net/http"
)
type Message struct {
Status string `json:"status"`
Message string `json:"message"`
}
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
response := Message{Status: "success", Message: "Hello, JSON!"}
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/json", jsonHandler)
http.ListenAndServe(":8080", nil)
}
Notes
- Here, we define a
Messagestruct to represent the JSON response. ThejsonHandlerfunction sets theContent-Typeheader toapplication/jsonand encodes theMessagestruct into JSON format. - You can test this by navigating to
http://localhost:8080/jsonin your web browser, which should display the JSON response.
Example 3: Serving Static Files
Context
This example shows how to create an HTTP server that serves static files from a directory. This is commonly used for web projects that include HTML, CSS, and JavaScript files.
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.ListenAndServe(":8080", nil)
}
Notes
- In this example, we use
http.FileServerto serve files from the./staticdirectory. Thehttp.StripPrefixfunction ensures that the URL path does not include the/static/prefix when accessing files. - To test this, create a
staticfolder in the same directory as your Go file and add some files (like HTML or images). You can access them viahttp://localhost:8080/static/yourfile.html.
Conclusion
These examples of creating a simple HTTP server in Go provide a solid foundation for building web applications and services. Whether you are responding with plain text, JSON, or serving static files, Go makes it straightforward to set up a functional server. Happy coding!
Related Topics
Explore More Go Code Snippets
Discover more examples and insights in this category.
View All Go Code Snippets