响应处理 #

一、响应状态码 #

1.1 设置状态码 #

go
app.Get("/ok", func(c *fiber.Ctx) error {
    return c.Status(200).SendString("OK")
})

app.Get("/created", func(c *fiber.Ctx) error {
    return c.Status(201).JSON(fiber.Map{"id": 1})
})

app.Get("/bad-request", func(c *fiber.Ctx) error {
    return c.Status(400).JSON(fiber.Map{"error": "Bad Request"})
})

app.Get("/unauthorized", func(c *fiber.Ctx) error {
    return c.Status(401).JSON(fiber.Map{"error": "Unauthorized"})
})

app.Get("/forbidden", func(c *fiber.Ctx) error {
    return c.Status(403).JSON(fiber.Map{"error": "Forbidden"})
})

app.Get("/not-found", func(c *fiber.Ctx) error {
    return c.Status(404).JSON(fiber.Map{"error": "Not Found"})
})

app.Get("/server-error", func(c *fiber.Ctx) error {
    return c.Status(500).JSON(fiber.Map{"error": "Internal Server Error"})
})

1.2 使用状态码常量 #

go
app.Get("/status", func(c *fiber.Ctx) error {
    return c.Status(fiber.StatusOK).JSON(fiber.Map{
        "message": "OK",
    })
})

// 常用状态码
fiber.StatusOK                  // 200
fiber.StatusCreated             // 201
fiber.StatusNoContent           // 204
fiber.StatusBadRequest          // 400
fiber.StatusUnauthorized        // 401
fiber.StatusForbidden           // 403
fiber.StatusNotFound            // 404
fiber.StatusMethodNotAllowed    // 405
fiber.StatusConflict            // 409
fiber.StatusTooManyRequests     // 429
fiber.StatusInternalServerError // 500
fiber.StatusServiceUnavailable  // 503

1.3 快捷方法 #

go
app.Get("/send-status", func(c *fiber.Ctx) error {
    return c.SendStatus(200)
})

二、JSON响应 #

2.1 基本JSON响应 #

go
app.Get("/json", func(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{
        "message": "Hello, World!",
        "status":  "ok",
    })
})

2.2 结构体JSON响应 #

go
type User struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

app.Get("/user", func(c *fiber.Ctx) error {
    user := User{
        ID:    "1",
        Name:  "John Doe",
        Email: "john@example.com",
    }
    return c.JSON(user)
})

app.Get("/users", func(c *fiber.Ctx) error {
    users := []User{
        {ID: "1", Name: "John", Email: "john@example.com"},
        {ID: "2", Name: "Jane", Email: "jane@example.com"},
    }
    return c.JSON(users)
})

2.3 JSONP响应 #

go
app.Get("/jsonp", func(c *fiber.Ctx) error {
    return c.JSONP(fiber.Map{
        "message": "Hello",
    }, "callback")
})

三、字符串响应 #

3.1 字符串响应 #

go
app.Get("/string", func(c *fiber.Ctx) error {
    return c.SendString("Hello, World!")
})

// 格式化字符串
app.Get("/format", func(c *fiber.Ctx) error {
    name := "Fiber"
    return c.SendString(fmt.Sprintf("Hello, %s!", name))
})

3.2 字节响应 #

go
app.Get("/bytes", func(c *fiber.Ctx) error {
    return c.Send([]byte("Hello, Bytes!"))
})

3.3 Send方法 #

go
app.Get("/send", func(c *fiber.Ctx) error {
    return c.Send([]byte("Hello"))
})

四、XML响应 #

4.1 基本XML响应 #

go
app.Get("/xml", func(c *fiber.Ctx) error {
    return c.XML(fiber.Map{
        "message": "Hello",
        "status":  "ok",
    })
})

4.2 结构体XML响应 #

go
type UserXML struct {
    XMLName xml.Name `xml:"user"`
    ID      string   `xml:"id"`
    Name    string   `xml:"name"`
    Email   string   `xml:"email"`
}

app.Get("/user-xml", func(c *fiber.Ctx) error {
    user := UserXML{
        ID:    "1",
        Name:  "John",
        Email: "john@example.com",
    }
    return c.XML(user)
})

五、HTML响应 #

5.1 直接返回HTML #

go
app.Get("/html", func(c *fiber.Ctx) error {
    html := `<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body><h1>Hello, World!</h1></body>
</html>`
    c.Set("Content-Type", "text/html")
    return c.SendString(html)
})

5.2 模板渲染 #

go
func main() {
    app := fiber.New()
    
    // 配置模板引擎
    app.Settings.Views = "./views"
    
    app.Get("/", func(c *fiber.Ctx) error {
        return c.Render("index", fiber.Map{
            "Title":   "Hello",
            "Message": "Welcome to Fiber!",
        })
    })
    
    app.Listen(":3000")
}

六、文件响应 #

6.1 发送文件 #

go
app.Get("/file", func(c *fiber.Ctx) error {
    return c.SendFile("./static/document.pdf")
})

// 压缩文件
app.Get("/compressed", func(c *fiber.Ctx) error {
    return c.SendFile("./static/large.json", true)
})

6.2 文件下载 #

go
app.Get("/download", func(c *fiber.Ctx) error {
    return c.Download("./static/document.pdf")
})

// 指定下载文件名
app.Get("/download-custom", func(c *fiber.Ctx) error {
    return c.Download("./static/document.pdf", "report.pdf")
})

6.3 附件响应 #

go
app.Get("/attachment", func(c *fiber.Ctx) error {
    c.Attachment("./static/document.pdf", "report.pdf")
    return c.SendFile("./static/document.pdf")
})

七、重定向 #

7.1 临时重定向(302) #

go
app.Get("/redirect", func(c *fiber.Ctx) error {
    return c.Redirect("/new-url")
})

7.2 永久重定向(301) #

go
app.Get("/permanent", func(c *fiber.Ctx) error {
    return c.Redirect("/new-url", 301)
})

7.3 外部重定向 #

go
app.Get("/external", func(c *fiber.Ctx) error {
    return c.Redirect("https://example.com")
})

7.4 路由重定向 #

go
app.Get("/old-route", func(c *fiber.Ctx) error {
    return c.Redirect("/new-route", 301)
})

app.Get("/new-route", func(c *fiber.Ctx) error {
    return c.SendString("New Route")
})

八、响应头 #

8.1 设置响应头 #

go
app.Get("/headers", func(c *fiber.Ctx) error {
    c.Set("Content-Type", "application/json")
    c.Set("X-Custom-Header", "value")
    c.Set("X-Request-ID", "12345")
    
    return c.JSON(fiber.Map{"message": "OK"})
})

8.2 追加响应头 #

go
app.Get("/append", func(c *fiber.Ctx) error {
    c.Append("Set-Cookie", "session=abc123")
    c.Append("Set-Cookie", "token=xyz789")
    
    return c.SendString("OK")
})

8.3 常用响应头 #

go
app.Get("/content-type", func(c *fiber.Ctx) error {
    c.Type("json")
    return c.SendString(`{"message": "Hello"}`)
})

app.Get("/cache", func(c *fiber.Ctx) error {
    c.Set("Cache-Control", "max-age=3600")
    return c.SendString("Cached content")
})

app.Get("/cors", func(c *fiber.Ctx) error {
    c.Set("Access-Control-Allow-Origin", "*")
    c.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    return c.SendString("CORS enabled")
})

九、流式响应 #

9.1 流式写入 #

go
app.Get("/stream", func(c *fiber.Ctx) error {
    c.Set("Content-Type", "text/event-stream")
    c.Set("Cache-Control", "no-cache")
    c.Set("Connection", "keep-alive")
    
    c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
        for i := 0; i < 10; i++ {
            fmt.Fprintf(w, "data: Message %d\n\n", i)
            w.Flush()
            time.Sleep(1 * time.Second)
        }
    })
    
    return nil
})

9.2 Server-Sent Events #

go
app.Get("/sse", func(c *fiber.Ctx) error {
    c.Set("Content-Type", "text/event-stream")
    c.Set("Cache-Control", "no-cache")
    c.Set("Connection", "keep-alive")
    
    c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
        for {
            data := fmt.Sprintf("data: %s\n\n", time.Now().Format(time.RFC3339))
            w.WriteString(data)
            w.Flush()
            time.Sleep(1 * time.Second)
        }
    })
    
    return nil
})

十、统一响应格式 #

10.1 响应结构体 #

go
type Response struct {
    Code    int         `json:"code"`
    Message string      `json:"message"`
    Data    interface{} `json:"data,omitempty"`
}

func Success(c *fiber.Ctx, data interface{}) error {
    return c.JSON(Response{
        Code:    0,
        Message: "success",
        Data:    data,
    })
}

func Error(c *fiber.Ctx, code int, message string) error {
    return c.JSON(Response{
        Code:    code,
        Message: message,
    })
}

// 使用
app.Get("/success", func(c *fiber.Ctx) error {
    return Success(c, fiber.Map{"name": "John"})
})

app.Get("/error", func(c *fiber.Ctx) error {
    return Error(c, 1001, "User not found")
})

10.2 分页响应 #

go
type PageResponse struct {
    Code    int         `json:"code"`
    Message string      `json:"message"`
    Data    interface{} `json:"data"`
    Page    int         `json:"page"`
    Limit   int         `json:"limit"`
    Total   int64       `json:"total"`
}

func PageSuccess(c *fiber.Ctx, data interface{}, page, limit int, total int64) error {
    return c.JSON(PageResponse{
        Code:    0,
        Message: "success",
        Data:    data,
        Page:    page,
        Limit:   limit,
        Total:   total,
    })
}

十一、总结 #

11.1 响应方法汇总 #

方法 用途
c.Status() 设置状态码
c.JSON() JSON响应
c.XML() XML响应
c.SendString() 字符串响应
c.Send() 字节响应
c.SendFile() 发送文件
c.Download() 文件下载
c.Redirect() 重定向
c.Set() 设置响应头
c.Render() 模板渲染

11.2 下一步 #

现在你已经掌握了响应处理,接下来让我们学习 Cookie与Session,了解会话管理!

最后更新:2026-03-28