首先创建项目结构并编写处理函数,接着在主程序中注册路由,最后运行服务器;通过HomeHandler返回HTML页面,ApiHandler返回JSON数据,静态资源由FileServer提供,使用StripPrefix正确映射路径,最终实现一个包含页面渲染、API响应和静态文件服务的完整Web服务器。

想快速上手 Golang 写一个简单的 Web 服务器?不需要复杂框架,用 Go 自带的 net/http 包就能轻松实现。本文带你从零开始搭建一个基础但完整的 Web 服务项目,适合初学者实战练习。
创建一个支持以下功能的简单 Web 服务器:
先创建项目目录并组织基本结构:
myweb/
├── main.go
├── handlers/
│ └── handlers.go
├── static/
│ ├── style.css
│ └── logo.png
└── templates/
└── index.html
这个结构清晰分离了逻辑代码、静态文件和页面模板,便于维护。
立即学习“go语言免费学习笔记(深入)”;
在 handlers/handlers.go 中定义请求处理逻辑:
package handlers
import (
"encoding/json"
"net/http"
"html/template"
)
// 首页处理器
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
tmpl, err := template.ParseFiles("../templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
}
// API 接口:返回 JSON
func ApiHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{
"message": "Hello from Go!",
"status": "success",
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
HomeHandler 渲染 HTML 页面,ApiHandler 返回结构化数据,两者职责分明。
在 main.go 中注册路由并启动服务:
package main
import (
"log"
"net/http"
"myweb/handlers"
)
func main() {
// 设置静态文件路由
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// 设置页面和 API 路由
http.HandleFunc("/", handlers.HomeHandler)
http.HandleFunc("/api", handlers.ApiHandler)
log.Println("服务器运行在 http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
</font>使用 http.Handle 提供静态资源,http.HandleFunc 注册动态路由。注意 StripPrefix 的作用是去掉 URL 前缀,正确映射文件路径。
在 templates/index.html 中写个简单页面:
<!DOCTYPE html> <html> <head> <title>Go Web 服务</title> <link rel="stylesheet" type="text/css" href="/static/style.css"> </head> <body> <h1>欢迎使用 Golang Web 服务</h1> <p>这是首页内容。</p> <img src="/static/logo.png" alt="Logo" width="200"> </body> </html>
static/style.css 可以加点样式让页面更美观:
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
h1 {
color: #007bff;
}
确保在项目根目录执行:
go mod init myweb go run main.go
打开浏览器访问:
如果看到页面加载成功、样式生效、API 返回 JSON,说明一切正常。
基本上就这些。这个小项目涵盖了 Web 服务的核心要素:路由、静态文件、动态响应和结构组织。你可以在此基础上添加表单处理、中间件、数据库连接等功能。不复杂但容易忽略细节,比如路径拼接和 Header 设置,动手试试就知道了。
以上就是Golang Web 简单 Web 服务器项目实战教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号