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

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

InitializeaGomodulewithgomodinit,2.InstallgqlgenCLI,3.Defineaschemainschema.graphqls,4.Rungqlgeninittogeneratemodelsandresolvers,5.Implementresolverfunctionsforqueriesandmutations,6.SetupanHTTPserverusingthegeneratedschema,and7.RuntheservertoaccessGr

Go uses time.Time structure to process dates and times, 1. Format and parse the reference time "2006-01-0215:04:05" corresponding to "MonJan215:04:05MST2006", 2. Use time.Date(year, month, day, hour, min, sec, nsec, loc) to create the date and specify the time zone such as time.UTC, 3. Time zone processing uses time.LoadLocation to load the position and use time.ParseInLocation to parse the time with time zone, 4. Time operation uses Add, AddDate and Sub methods to add and subtract and calculate the interval.

Use the template.ParseFS and embed package to compile HTML templates into binary files. 1. Import the embed package and embed the template file into the embed.FS variable with //go:embedtemplates/.html; 2. Call template.Must(template.ParseFS(templateFS,"templates/.html")))) to parse all matching template files; 3. Render the specified in the HTTP processor through tmpl.ExecuteTemplate(w,"home.html", nil)
