我参与了HNG13实习项目,阶段0的任务是构建一个简单的API来返回个人资料和随机猫事实。我选择使用Go语言和Gin框架来完成这个任务。
当访问端点 /me 时,API返回:
示例响应:
{
"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响应的知识。在开发中增添一些乐趣总是好的——还有什么比随机猫事实更让人愉悦的呢?
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。