登录
首页 >  Golang >  Go教程

Golang搭建简单HTTPAPI教程

时间:2025-09-25 21:03:38 444浏览 收藏

**Golang构建简单HTTP API教程:快速入门与实践** 想快速搭建HTTP API服务吗?本文将手把手教你使用Golang标准库`net/http`,无需任何第三方框架,轻松构建功能完善的API接口。我们将从创建基本的HTTP服务器入手,通过`http.ListenAndServe`启动服务,并利用`http.HandleFunc`注册路由。重点讲解如何实现GET接口返回JSON数据,以及POST接口接收并解析JSON请求。通过示例代码,详细展示`helloHandler`和`dataHandler`的实现,包括设置Content-Type、使用`json.NewEncoder`进行JSON编码/解码等关键步骤。最后,提供详细的测试方法,让你快速验证API功能。本文适用于轻量级服务,是Golang API开发的入门指南,为你后续学习高级路由和Web框架打下坚实基础。

使用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接口示例

用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学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>