It is not difficult to build a web server written in Go. The core lies in using the net/http package to implement basic services. 1. Use net/http to start the simplest server: register processing functions and listen to ports through a few lines of code; 2. Routing management: Use ServeMux to organize multiple interface paths for easy structured management; 3. Common practices: group routing by functional modules, and use third-party libraries to support complex matching; 4. Static file service: Provide HTML, CSS and JS files through http.FileServer; 5. Performance and security: Enable HTTPS, limit request body size, and set timeout to improve security and performance. After mastering these key points, it will be easier to expand functionality.
Building a web server written in Go is not difficult, especially if you are already familiar with the basic Go syntax. The net/http
package in Go standard library is powerful enough to enable you to quickly start a simple HTTP service. Below are some practical steps and suggestions to help you successfully build your own web server.

Basic settings: Use net/http to start a simplest server
Go's standard library comes with a very practical HTTP package, you can run a web server with a few lines of code.
package main import ( "fmt" "net/http" ) func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", helloHandler) fmt.Println("Starting server at port 8080...") if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } }
This code registers a handler that handles the root path /
and listens for the local 8080 port. Visit http://localhost:8080
to see the output content.

hint:
- The first parameter of the processing function is
http.ResponseWriter
, which is used to write the response content. - The second parameter is
*http.Request
, which can obtain the request information. - The second parameter of
http.ListenAndServe
is generally passednil
, indicating that the default multiplexer (router manager) is used.
Routing Management: How to organize multiple interface paths
As the functionality increases, you may need to set different processing logic for different URL paths. Although http.HandleFunc
is convenient, it is more suitable for small projects. For projects with clearer structures, it is recommended to use ServeMux
:

mux := http.NewServeMux() mux.HandleFunc("/hello", helloHandler) mux.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "About page") }) http.ListenAndServe(":8080", mux)
This allows centralized management of processing functions for different paths, and facilitates later replacement of middleware or custom routing logic.
Common practices:
- Group routing by functional module
- Use third-party routing libraries such as
chi
orgorilla/mux
to achieve more complex routing matching (such as paths with parameters)
Static file service: enables the server to provide HTML, CSS and JS as well
If you want to provide static resources (such as front-end pages), you can quickly implement it through http.FileServer
:
fs := http.FileServer(http.Dir("static")) http.Handle("/static/", http.StripPrefix("/static/", fs))
This code will map the static
folder in the current directory to the /static/
path and automatically process the static file requests therein.
Notes:
The path prefix needs to be removed with
StripPrefix
, otherwise the file cannot be foundIf you want to use a directory as the homepage, you can use:
http.Handle("/", http.FileServer(http.Dir("./public")))
Performance and Safety: Several Points that are Easily Neglected But Important
Although the above method can quickly build a server, some performance and security issues need to be paid attention to in a production environment:
- Using HTTPS: You can start HTTPS service with
http.ListenAndServeTLS
, or cooperate with a reverse proxy (such as Nginx) - Limit request body size: There is no limit by default, malicious users may upload large files and cause memory exhaustion
- Set timeout: Create a server instance with timeout in the main function to avoid slow requests to drag down the service
- Enable GOMAXPROCS: Although Go 1.5 enables multi-core support by default, if you deploy it on a multi-core machine, it is recommended to confirm it.
Basically that's it. Writing a web server in Go is very fast to get started and has good performance. As long as you master the infrastructure, it will not be difficult to expand various functions in the future.
The above is the detailed content of How to build a web server in Go. For more information, please follow other related articles on the PHP Chinese website!
- Using HTTPS: You can start HTTPS service with

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)

Hot Topics

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

In Go, an interface is a type that defines behavior without specifying implementation. An interface consists of method signatures, and any type that implements these methods automatically satisfy the interface. For example, if you define a Speaker interface that contains the Speak() method, all types that implement the method can be considered Speaker. Interfaces are suitable for writing common functions, abstract implementation details, and using mock objects in testing. Defining an interface uses the interface keyword and lists method signatures, without explicitly declaring the type to implement the interface. Common use cases include logs, formatting, abstractions of different databases or services, and notification systems. For example, both Dog and Robot types can implement Speak methods and pass them to the same Anno

Go's time package provides functions for processing time and duration, including obtaining the current time, formatting date, calculating time difference, processing time zone, scheduling and sleeping operations. To get the current time, use time.Now() to get the Time structure, and you can extract specific time information through Year(), Month(), Day() and other methods; use Format("2006-01-0215:04:05") to format the time string; when calculating the time difference, use Sub() or Since() to obtain the Duration object, and then convert it into the corresponding unit through Seconds(), Minutes(), and Hours();

InGo,ifstatementsexecutecodebasedonconditions.1.Basicstructurerunsablockifaconditionistrue,e.g.,ifx>10{...}.2.Elseclausehandlesfalseconditions,e.g.,else{...}.3.Elseifchainsmultipleconditions,e.g.,elseifx==10{...}.4.Variableinitializationinsideif,l

Gohandlesconcurrencyusinggoroutinesandchannels.1.GoroutinesarelightweightfunctionsmanagedbytheGoruntime,enablingthousandstorunconcurrentlywithminimalresourceuse.2.Channelsprovidesafecommunicationbetweengoroutines,allowingvaluestobesentandreceivedinas

Use bit operators to operate specific bits of integers in Go language, suitable for processing flag bits, underlying data, or optimization operations. 1. Use & (bit-wise) to check whether a specific bit is set; 2. Use

The standard way to protect critical areas in Go is to use the Lock() and Unlock() methods of sync.Mutex. 1. Declare a mutex and use it with the data to be protected; 2. Call Lock() before entering the critical area to ensure that only one goroutine can access the shared resources; 3. Use deferUnlock() to ensure that the lock is always released to avoid deadlocks; 4. Try to shorten operations in the critical area to improve performance; 5. For scenarios where more reads and less writes, sync.RWMutex should be used, read operations through RLock()/RUnlock(), and write operations through Lock()/Unlock() to improve concurrency efficiency.

A switch statement in Go is a control flow tool that executes different code blocks based on the value of a variable or expression. 1. Switch executes corresponding logic by matching cases, and does not support the default fall-through; 2. The conditions can be omitted and Boolean expressions are used as case judgment; 3. A case can contain multiple values, separated by commas; 4. Support type judgment (typeswitch), which is used to dynamically check the underlying types of interface variables. This makes switch easier and more efficient than long chain if-else when dealing with multi-condition branches, value grouping and type checking.
