使用Golang标准库net/http可快速构建HTTP API,无需第三方框架。首先通过http.ListenAndServe启动服务器,并用http.HandleFunc注册路由。接着定义helloHandler处理GET请求,返回JSON格式数据,设置Content-Type头为application/json,利用json.NewEncoder编码响应。然后实现dataHandler处理POST请求,读取请求体中的JSON数据,反序列化到InputData结构体,验证并返回确认信息。最后通过访问/hello或使用curl测试POST接口验证功能。该方法适用于轻量级服务,后续可扩展使用高级路由或框架。

用Golang构建基础的HTTP API非常简单,标准库net/http已经提供了足够的能力,无需引入第三方框架也能快速实现。下面是一个完整的示例,展示如何创建一个简单的API,支持GET和POST请求。
使用http.ListenAndServe启动一个监听在指定端口的服务器。通过http.HandleFunc注册路由和处理函数。
package main
import (
"net/http"
)
func main() {
// 注册路由
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/data", dataHandler)
// 启动服务器
http.ListenAndServe(":8080", nil)
}
定义一个结构体用于响应数据,使用json.Marshal将Go结构编码为JSON,并设置正确的Content-Type头。
import (
"encoding/json"
"net/http"
)
type Response struct {
Message string `json:"message"`
Status int `json:"status"`
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
resp := Response{Message: "Hello from Go!", Status: 200}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
读取请求体中的JSON数据,反序列化到结构体中,并返回确认信息。
立即学习“go语言免费学习笔记(深入)”;
type InputData struct {
Name string `json:"name"`
}
func dataHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
return
}
var input InputData
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
response := map[string]string{
"received": "Hello, " + input.Name,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
启动服务后,可通过以下方式测试:
http://localhost:8080/hello,应返回JSON消息
curl -X POST http://localhost:8080/data \
-H "Content-Type: application/json" \
-d '{"name": "Alice"}'
预期返回:{"received":"Hello, Alice"}
基本上就这些。Golang的标准库足够支撑一个轻量级API服务,适合学习或小型项目。随着需求增长,可逐步引入路由库(如gorilla/mux)或Web框架(如Echo、Gin)提升开发效率。
以上就是Golang构建基础HTTP API接口示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号