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)

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.

The if-else statement in Go does not require brackets but must use curly braces. It supports initializing variables in if to limit scope. The conditions can be judged through the elseif chain, which is often used for error checking. The combination of variable declaration and conditions can improve the simplicity and security of the code.

In Go, constants are declared using the const keyword, and the value cannot be changed, and can be of no type or type; 1. A single constant declaration such as constPi=3.14159; 2. Multiple constant declarations in the block are such as const(Pi=3.14159; Language="Go"; IsCool=true); 3. Explicit type constants such as constSecondsInMinuteint=60; 4. Use iota to generate enumeration values, such as const(Sunday=iota;Monday;Tuesday) will assign values 0, 1, and 2 in sequence, and iota can be used for expressions such as bit operations; constants must determine the value at compile time,

gorun is a command for quickly compiling and executing Go programs. 1. It completes compilation and running in one step, generates temporary executable files and deletes them after the program is finished; 2. It is suitable for independent programs containing main functions, which are easy to develop and test; 3. It supports multi-file operation, and can be executed through gorun*.go or lists all files; 4. It automatically processes dependencies and uses the module system to parse external packages; 5. It is not suitable for libraries or packages, and does not generate persistent binary files. Therefore, it is suitable for rapid testing during scripts, learning and frequent modifications. It is an efficient and concise way of running.

To connect to SQL databases in Go, you need to use the database/sql package and a specific database driver. 1. Import database/sql packages and drivers (such as github.com/go-sql-driver/mysql), note that underscores before the drivers indicate that they are only used for initialization; 2. Use sql.Open("mysql","user:password@tcp(localhost:3306)/dbname") to create a database handle, and call db.Ping() to verify the connection; 3. Use db.Query() to execute query, and db.Exec() to execute
