使用Go和Gin构建个人资料与随机猫事实API

构建简单Go API返回个人资料和随机猫事实

我参与了HNG13实习项目,阶段0的任务是构建一个简单的API来返回个人资料和随机猫事实。我选择使用Go语言和Gin框架来完成这个任务。

🔧 技术栈

  • Go (Golang)
  • Gin - HTTP Web框架
  • catfact.ninja API - 获取随机猫事实的免费API

🛠️ API功能

当访问端点 /me 时,API返回:

  • 姓名、邮箱和技术栈
  • 当前时间戳(UTC)
  • 随机猫事实 🐱

示例响应:

{
  "status": "success",
  "user": {
    "email": "",
    "name": "",
    "stack": "Go/Gin"
  },
  "timestamp": "2025-10-21T14:42:11Z",
  "fact": "Cats sleep for 70% of their lives."
}

🚀 控制器设置

核心逻辑位于控制器中:

package controllers

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

func GetProfile(c *gin.Context) {
    ctx := c.Request.Context()

    fact, err := fetchCatFact(ctx)
    if err != nil {
        log.Printf("Error fetching cat fact: %v", err)
        fact = "Unable to fetch cat fact at this time. Did you know cats are amazing creatures?"
    }

    c.JSON(200, gin.H{
        "status": "success",
        "user": gin.H{
            "email": "<your-email>",
            "name": "<your-name>",
            "stack": "Go/Gin",
        },
        "timestamp": time.Now().UTC().Format(time.RFC3339),
        "fact":      fact,
    })
}

🐾 获取猫事实

此函数处理调用catfact.ninja API并解析响应:

func fetchCatFact(ctx context.Context) (string, error) {
    catFactAPIURL := "https://catfact.ninja/fact"

    req, err := http.NewRequestWithContext(ctx, http.MethodGet, catFactAPIURL, nil)
    if err != nil {
        return "", fmt.Errorf("failed to create request: %w", err)
    }

    req.Header.Set("Accept", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", fmt.Errorf("failed to fetch cat fact: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("cat fact API returned status: %d", resp.StatusCode)
    }

    type CatFactResponse struct {
        Fact   string `json:"fact"`
        Length int    `json:"length"`
    }
    var catFact CatFactResponse
    if err := json.NewDecoder(resp.Body).Decode(&catFact); err != nil {
        return "", fmt.Errorf("failed to decode response: %w", err)
    }

    return catFact.Fact, nil
}

🌐 路由设置

/me 路径下创建路由:

package routes

import (
    "profile-api/internal/controllers"
    "github.com/gin-gonic/gin"
)

func RegisterRoutes() {
    r := gin.Default()

    // 可选:跳过ngrok浏览器警告
    r.Use(func(c *gin.Context) {
        c.Header("ngrok-skip-browser-warning", "1")
        c.Next()
    })

    r.GET("/me", controllers.GetProfile)

    r.Run(":8080") // 在8080端口启动服务器
}

🧪 测试

运行应用:

go run main.go

然后访问:http://localhost:8080/me

应该能看到个人资料和随机猫事实以JSON格式返回。

📌 总结

这是一个小而有趣的项目,巩固了在Go中使用上下文、外部API和构建结构化JSON响应的知识。在开发中增添一些乐趣总是好的——还有什么比随机猫事实更让人愉悦的呢?
更多精彩内容 请关注我的个人公众号 公众号(办公AI智能小助手)或者 我的个人博客 https://blog.qife122.com/
对网络安全、黑客技术感兴趣的朋友可以关注我的安全公众号(网络安全技术点滴分享)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值