How to build a simple web server in Golang?
Aug 01, 2025 am 07:02 AMImport the net/http package and define the processing function, use http.HandleFunc to register the processor of the root path, and then call http.ListenAndServe(":8080", nil) to start the server; 2. Register independent processors for different paths such as "/about" through http.HandleFunc to achieve multi-routing; 3. Use http.FileServer to combine http.StripPrefix and http.Handle to provide access to the files in the static/ directory through the /static/ path, and optionally define homeHandler to return to the main page; 4. Use http.NewServeMux to create a router multiplexer, and use custom http.Server instances to obtain advanced configuration control capabilities such as timeout and TLS; in summary, a lightweight web server with routing, static file services and extensible configuration can be built through the Go standard library net/http, which is suitable for learning and simple applications, without the need for third-party frameworks.
Building a simple web server in Golang is straightforward thanks to the net/http
package, which is part of Go's standard library. You don't need external dependencies for basic functionality. Here's how to do it step by step.

? 1. Set up a basic HTTP server
Start by importing the required packages and defining a handler function:
package main import ( "fmt" "net/http" ) func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World! This is a simple Go web server.") } func main() { http.HandleFunc("/", helloHandler) fmt.Println("Server starting on :8080...") http.ListenAndServe(":8080", nil) }
What this does:

-
http.HandleFunc("/", helloHandler)
registers thehelloHandler
function to handle requests to the root path/
. -
http.ListenAndServe(":8080", nil)
starts the server on port 8080. - The
helloHandler
writes a simple response to the client.
Run it with:
go run main.go
Then visit http://localhost:8080
in your browser.

? 2. Add multiple routes
You can define different handlers for different paths:
func aboutHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "About page - Built with Go!") } func main() { http.HandleFunc("/", helloHandler) http.HandleFunc("/about", aboutHandler) fmt.Println("Server running on http://localhost:8080") http.ListenAndServe(":8080", nil) }
Now:
-
GET /
→ "Hello, World!" -
GET /about
→ "About page - Built with Go!"
? 3. Serve static files (like HTML, CSS, JS)
Suppose you have a folder static/
with an index.html
file.
func main() { fs := http.FileServer(http.Dir("static/")) http.Handle("/static/", http.StripPrefix("/static/", fs)) http.HandleFunc("/", homeHandler) // Optional: render home page fmt.Println("Server on :8080") http.ListenAndServe(":8080", nil) }
With this:
- Files in
static/
are served under/static/...
- For example,
static/index.html
→ accessible athttp://localhost:8080/static/index.html
And your homeHandler
could be:
func homeHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "static/index.html") }
? 4. Use a custom server for better control
Instead of http.ListenAndServe
, use http.Server
for timeouts and graceful shutdowns:
func main() { mux := http.NewServeMux() mux.HandleFunc("/", helloHandler) mux.HandleFunc("/about", aboutHandler) server := &http.Server{ Addr: ":8080", Handler: mux, } fmt.Println("Server starting on :8080") if err := server.ListenAndServe(); err != nil { fmt.Printf("Server failed: %v\n", err) } }
This gives you more control over configuration (like timeouts, TLS, etc.).
Tips & Best Practices
- Always validate input in real apps (headers, query params, body).
- Avoid
nil
handler inListenAndServe
if using a customServeMux
. - For production, consider using routers like
gorilla/mux
orchi
, but for learning or simple APIs,net/http
is perfect. - Handle errors properly (eg, file not found, bad requests).
That's it — you've built a working web server in Go with routing and static file support. It's minimal, fast, and doesn't need a framework.
The above is the detailed content of How to build a simple web server in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

IIS is a web server software developed by Microsoft to host websites and applications. 1. Installing IIS can be done through the "Add Roles and Features" wizard in Windows. 2. Creating a website can be achieved through PowerShell scripts. 3. Configure URL rewrites can be implemented through web.config file to improve security and SEO. 4. Debugging can be done by checking IIS logs, permission settings and performance monitoring. 5. Optimizing IIS performance can be achieved by enabling compression, configuring caching and load balancing.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Reasons for IIS' popularity include its high performance, scalability, security and flexible management capabilities. 1) High performance and scalability With built-in performance monitoring tools and modular design, IIS can optimize and expand server capabilities in real time. 2) Security provides SSL/TLS support and URL authorization rules to protect website security. 3) Application pool ensures server stability by isolating different applications. 4) Management and monitoring simplifies server management through IISManager and PowerShell scripts.
