Learn step-by-step how to build a simple yet functional HTTP server in Golang using only the standard library. This beginner-friendly guide will walk you through setting up a project, structuring your application, and running a basic HTTP server.
Prerequisites
Before starting, ensure you have the following:
prerequisites
- Go Programming Language: Installed on your system. Download it from the official Go installation page and verify it with
go version. - Basic Programming Knowledge: Familiarity with concepts like functions, variables, and conditionals.
- Command-Line Basics: Comfort navigating directories and running commands in a terminal.
Set Up the Environment
Initialize the project and prepare the directory structure.
steps
Create a new folder and navigate to it:
bashmkdir go_http_server cd go_http_serverInitialize a Go module:
bashgo mod init go_http_serverThis creates a
go.modfile that defines your module and tracks dependencies.Verify the setup:
- Ensure
go.modis created within your folder. - Check the Go version with:bash
go version
- Ensure
Create and Structure the Application
Use a standard Go project layout to keep the code organized.
file tree
go_http_server/
├── cmd/
│ └── server/
│ └── main.go
└── go.modcmd/server/main.go: This will hold the entry point for running the HTTP server.
Building the HTTP Server
We'll now create a minimal HTTP server using the net/http package.
steps
Navigate to the
cmd/serverdirectory:bashcd cmd/serverCreate and edit
main.go:bashnano main.goStart with the following Go code:
package main import ( "fmt" "net/http" ) // handler function that responds to HTTP requests func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { // Register the handler function to an endpoint http.HandleFunc("/", helloHandler) // Start the HTTP server on port 8080 fmt.Println("Starting server on :8080") if err := http.ListenAndServe(":8080", nil); err != nil { fmt.Println("Error starting server:", err) } }- This code defines a
helloHandlerfunction for responding with"Hello, World!"and starts the server on port8080.
- This code defines a
Run the server:
bashgo run main.goVerify the server:
- Open a browser and navigate to
http://localhost:8080. - You should see
Hello, World!displayed.
- Open a browser and navigate to
Verifying the Server Setup
Debug your server and ensure the setup is functional.
Tips for Beginners
FAQ
Can I use HTTPS with this HTTP server?
Yes, you can use http.ListenAndServeTLS to serve HTTPS requests by providing a certificate and private key.
How do I add more endpoints?
Register more handlers by calling http.HandleFunc with different paths and handler functions.
What is the difference between http.Handle and http.HandleFunc?
http.HandleFunc simplifies registering handlers by accepting a standard function signature, while http.Handle works with objects implementing the http.Handler interface.
Official reference: Go documentation.