登录
首页 >  Golang >  Go教程

Golang搭建简单HTTPAPI教程

时间:2026-05-09 17:10:07 481浏览 收藏

本文手把手教你仅用Golang标准库net/http快速搭建一个轻量、健壮的HTTP API服务,无需依赖任何第三方框架:从启动服务器、注册路由,到实现支持JSON响应的GET接口(/hello)和可解析请求体的POST接口(/data),全程代码简洁清晰,并附带curl测试示例;它不仅适合初学者入门Go Web开发,也足以支撑小型生产项目,后续还可平滑扩展为更复杂的路由与架构。

Golang构建基础HTTP API接口示例

用Golang构建基础的HTTP API非常简单,标准库net/http已经提供了足够的能力,无需引入第三方框架也能快速实现。下面是一个完整的示例,展示如何创建一个简单的API,支持GET和POST请求。

1. 创建基本的HTTP服务器

使用http.ListenAndServe启动一个监听在指定端口的服务器。通过http.HandleFunc注册路由和处理函数。

package main

import (
    "net/http"
)

func main() {
    // 注册路由
    http.HandleFunc("/hello", helloHandler)
    http.HandleFunc("/data", dataHandler)

    // 启动服务器
    http.ListenAndServe(":8080", nil)
}

2. 实现GET接口:返回JSON数据

定义一个结构体用于响应数据,使用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)
}

3. 实现POST接口:接收并解析JSON

读取请求体中的JSON数据,反序列化到结构体中,并返回确认信息。

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)
}

4. 测试你的API

启动服务后,可通过以下方式测试:

  • GET请求: 访问 http://localhost:8080/hello,应返回JSON消息
  • POST请求: 使用curl发送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搭建简单HTTPAPI教程》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>