Golang中的API响应解析 - Kubesimplify博客

作者:API传播员 · 2026-01-15 · 阅读时间:5分钟

在本教程中,我们将学习如何在 Golang 中实现一个简单的 API 请求/响应流程。通过编写一个 Go 程序,我们将展示如何处理来自 API 的请求并生成响应。


导入必要的包

首先,我们需要从 Go 标准库中导入以下两个包:

  • http:用于处理 HTTP 请求和响应。
  • fmt:用于格式化输出。

http 包提供了 ResponseWriter(用于发送响应数据)和 Request(用于读取 API 请求)的功能。


创建处理程序函数

接下来,我们创建一个处理程序函数,该函数接收两个参数:

  • ResponseWriter:用于写入响应数据。
  • Request:用于读取客户端发送的请求。

以下是处理程序函数的代码示例:

func handleMe(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "我们找到了!")
}

通过 fmt.Fprintf 函数,我们可以向 ResponseWriter 对象写入响应数据。


路由和启动服务器

要将 URL 路径路由到处理程序函数,我们使用 http.HandleFunc 函数。例如:

http.HandleFunc("/", handleMe)

最后,我们通过 http.ListenAndServe 函数启动服务器并监听指定端口:

http.ListenAndServe(":8181", nil)

完整的代码如下:

package main

import (
    "fmt"
    "net/http"
)func handleMe(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "我们找到了!")
}func main() {
    http.HandleFunc("/", handleMe)
    http.ListenAndServe(":8181", nil)
}

运行程序:

go run main.go

添加另一个处理程序路径

我们可以为不同的路径添加新的处理程序。例如:

func handleFollow(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Follow Kubesimple")
}

main 函数中添加路由:

http.HandleFunc("/follow", handleFollow)

运行程序后,访问以下路径即可触发不同的处理程序:

  • http://localhost:8181/
  • http://localhost:8181/follow

处理 JSON 响应

在与 JSON 数据。为了生成 JSON 响应,我们需要定义一个结构体并使用 json 包进行编码。

定义结构体

以下是一个示例结构体:

type Kubesimple struct {
    Website  string json:"website"
    Twitter  string json:"twitter"
    Sponsor  string json:"sponsor"
    Founder  string json:"founder"
}

创建 JSON 处理程序

我们可以创建一个处理程序函数来生成 JSON 响应:

func handleJson(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    kubesimple := Kubesimple{
        Website: "kubesimple.com",
        Twitter: "@kubesimple",
        Sponsor: "kubesimple.com/sponsor",
        Founder: "Saiyam Pathak",
    }
    json.NewEncoder(w).Encode(kubesimple)
}

main 函数中添加路由:

http.HandleFunc("/json", handleJson)

运行程序后,使用 curl 命令测试:

curl http://localhost:8181/json

返回结果示例:

{
    "website": "kubesimple.com",
    "twitter": "@kubesimple",
    "sponsor": "kubesimple.com/sponsor",
    "founder": "Saiyam Pathak"
}

处理 HTML 响应

除了 JSON 响应,我们还可以返回 HTML 响应。为此,我们需要使用 html/template 包。

创建 HTML 文件

首先,创建一个 HTML 文件(例如 demo.html):




    Kubesimple


    

欢迎来到 Kubesimple

创建 HTML 处理程序

以下是处理 HTML 响应的代码:

func handleHtml(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    tmpl, _ := template.ParseFiles("demo.html")
    tmpl.Execute(w, nil)
}

main 函数中添加路由:

http.HandleFunc("/html", handleHtml)

运行程序后,访问 http://localhost:8181/html 即可查看 HTML 响应。


总结

通过本教程,我们学习了如何在 Golang 中创建一个简单的 API,并实现以下功能:

  1. 返回纯文本响应。
  2. 返回 JSON 响应。
  3. 返回 HTML 响应。

这些示例展示了如何使用 Go 的标准库构建高效的 Web 服务。希望本文对您有所帮助!

原文链接: https://blog.kubesimplify.com/api-response-in-go