第一个应用 #

一、Hello World #

1.1 创建项目 #

bash
# 创建项目目录
mkdir hello-fiber
cd hello-fiber

# 初始化模块
go mod init hello-fiber

# 安装Fiber
go get -u github.com/gofiber/fiber/v2

1.2 编写代码 #

创建 main.go 文件:

go
package main

import "github.com/gofiber/fiber/v2"

func main() {
    // 创建Fiber实例
    app := fiber.New()
    
    // 定义GET路由
    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, Fiber!")
    })
    
    // 启动HTTP服务,默认监听:3000
    app.Listen(":3000")
}

1.3 运行项目 #

bash
# 运行项目
go run main.go

# 输出
┌───────────────────────────────────────────────────┐
│                    hello-fiber                    │
│                   Fiber v2.51.0                   │
│               http://127.0.0.1:3000               │
│       (bound on host 0.0.0.0 and port 3000)       │
│                                                   │
│ Handlers ............. 1  Processes ........... 1 │
│ Id ................. 1s0  PID ............. 12345 │
└───────────────────────────────────────────────────┘

1.4 测试接口 #

bash
# 使用curl测试
curl http://localhost:3000/

# 输出
Hello, Fiber!

二、代码解析 #

2.1 创建应用实例 #

go
// 创建默认配置的应用
app := fiber.New()

// 创建自定义配置的应用
app := fiber.New(fiber.Config{
    AppName:      "My App",
    StrictRouting: true,
    CaseSensitive: true,
})

2.2 定义路由 #

go
// GET请求
app.Get("/get", func(c *fiber.Ctx) error {
    return c.SendString("GET request")
})

// POST请求
app.Post("/post", func(c *fiber.Ctx) error {
    return c.SendString("POST request")
})

// PUT请求
app.Put("/put", func(c *fiber.Ctx) error {
    return c.SendString("PUT request")
})

// DELETE请求
app.Delete("/delete", func(c *fiber.Ctx) error {
    return c.SendString("DELETE request")
})

// PATCH请求
app.Patch("/patch", func(c *fiber.Ctx) error {
    return c.SendString("PATCH request")
})

// HEAD请求
app.Head("/head", func(c *fiber.Ctx) error {
    return c.SendString("HEAD request")
})

// OPTIONS请求
app.Options("/options", func(c *fiber.Ctx) error {
    return c.SendString("OPTIONS request")
})

// 匹配所有HTTP方法
app.All("/all", func(c *fiber.Ctx) error {
    return c.SendString("All methods")
})

2.3 处理函数 #

go
// 匿名函数
app.Get("/anonymous", func(c *fiber.Ctx) error {
    return c.SendString("Anonymous function")
})

// 命名函数
func helloHandler(c *fiber.Ctx) error {
    return c.SendString("Named function")
}
app.Get("/named", helloHandler)

// 方法绑定
type UserController struct{}

func (u *UserController) Hello(c *fiber.Ctx) error {
    return c.SendString("Method handler")
}
user := &UserController{}
app.Get("/method", user.Hello)

2.4 启动服务器 #

go
// 默认端口3000
app.Listen(":3000")

// 指定端口
app.Listen(":8080")

// 指定地址和端口
app.Listen("127.0.0.1:8080")

// 使用TLS
app.Listen(":443", fiber.ListenConfig{
    CertFile: "./cert.pem",
    KeyFile:  "./key.pem",
})

// 使用自定义Listener
ln, _ := net.Listen("tcp", ":3000")
app.Listener(ln)

三、Context上下文 #

3.1 Context简介 #

Context是Fiber的核心,封装了请求和响应:

go
func handler(c *fiber.Ctx) error {
    // c.Request()  - *fasthttp.Request
    // c.Response() - *fasthttp.Response
    return nil
}

3.2 获取请求参数 #

go
app.Get("/query", func(c *fiber.Ctx) error {
    // 获取查询参数
    name := c.Query("name")              // 获取name参数
    name = c.Query("name", "Guest")      // 带默认值
    
    return c.SendString("Hello " + name)
})

3.3 获取路径参数 #

go
// 获取路径参数
app.Get("/user/:id", func(c *fiber.Ctx) error {
    id := c.Params("id")
    return c.SendString("User ID: " + id)
})

// 获取可选路径参数
app.Get("/user/:id?", func(c *fiber.Ctx) error {
    id := c.Params("id", "default")
    return c.SendString("User ID: " + id)
})

// 获取整数参数
app.Get("/page/:num", func(c *fiber.Ctx) error {
    num := c.ParamsInt("num", 1)
    return c.SendString("Page: " + strconv.Itoa(num))
})

3.4 获取表单数据 #

go
app.Post("/form", func(c *fiber.Ctx) error {
    // 获取表单数据
    username := c.FormValue("username")
    password := c.FormValue("password", "")
    
    return c.SendString("Username: " + username)
})

3.5 获取JSON数据 #

go
app.Post("/json", func(c *fiber.Ctx) error {
    // 方式1:解析到结构体
    type User struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }
    var user User
    if err := c.BodyParser(&user); err != nil {
        return err
    }
    
    return c.JSON(user)
})

四、响应处理 #

4.1 字符串响应 #

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

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

4.2 JSON响应 #

go
// 使用fiber.Map
app.Get("/json1", func(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{
        "message": "ok",
        "status":  200,
    })
})

// 使用结构体
app.Get("/json2", func(c *fiber.Ctx) error {
    type Response struct {
        Message string `json:"message"`
        Status  int    `json:"status"`
    }
    return c.JSON(Response{
        Message: "ok",
        Status:  200,
    })
})

4.3 XML响应 #

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

4.4 HTML响应 #

go
app.Get("/html", func(c *fiber.Ctx) error {
    return c.SendString("<h1>Hello, HTML!</h1>")
})

// 设置Content-Type
app.Get("/html2", func(c *fiber.Ctx) error {
    c.Set("Content-Type", "text/html")
    return c.SendString("<h1>Hello, HTML!</h1>")
})

4.5 文件响应 #

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

// 文件下载
app.Get("/download", func(c *fiber.Ctx) error {
    return c.Download("./static/file.pdf", "document.pdf")
})

4.6 重定向 #

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

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

app.Get("/new-url", func(c *fiber.Ctx) error {
    return c.SendString("Redirected!")
})

五、完整示例 #

5.1 RESTful API示例 #

go
package main

import (
    "github.com/gofiber/fiber/v2"
)

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var users = []User{
    {ID: "1", Name: "Alice", Age: 25},
    {ID: "2", Name: "Bob", Age: 30},
}

func main() {
    app := fiber.New()
    
    // 获取所有用户
    app.Get("/users", func(c *fiber.Ctx) error {
        return c.JSON(users)
    })
    
    // 获取单个用户
    app.Get("/users/:id", func(c *fiber.Ctx) error {
        id := c.Params("id")
        for _, user := range users {
            if user.ID == id {
                return c.JSON(user)
            }
        }
        return c.Status(404).JSON(fiber.Map{
            "error": "User not found",
        })
    })
    
    // 创建用户
    app.Post("/users", func(c *fiber.Ctx) error {
        var user User
        if err := c.BodyParser(&user); err != nil {
            return c.Status(400).JSON(fiber.Map{
                "error": err.Error(),
            })
        }
        users = append(users, user)
        return c.Status(201).JSON(user)
    })
    
    // 更新用户
    app.Put("/users/:id", func(c *fiber.Ctx) error {
        id := c.Params("id")
        var updatedUser User
        if err := c.BodyParser(&updatedUser); err != nil {
            return c.Status(400).JSON(fiber.Map{
                "error": err.Error(),
            })
        }
        for i, user := range users {
            if user.ID == id {
                users[i] = updatedUser
                users[i].ID = id
                return c.JSON(users[i])
            }
        }
        return c.Status(404).JSON(fiber.Map{
            "error": "User not found",
        })
    })
    
    // 删除用户
    app.Delete("/users/:id", func(c *fiber.Ctx) error {
        id := c.Params("id")
        for i, user := range users {
            if user.ID == id {
                users = append(users[:i], users[i+1:]...)
                return c.JSON(fiber.Map{
                    "message": "Deleted",
                })
            }
        }
        return c.Status(404).JSON(fiber.Map{
            "error": "User not found",
        })
    })
    
    app.Listen(":3000")
}

5.2 测试API #

bash
# 获取所有用户
curl http://localhost:3000/users

# 获取单个用户
curl http://localhost:3000/users/1

# 创建用户
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"id":"3","name":"Charlie","age":28}'

# 更新用户
curl -X PUT http://localhost:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"id":"1","name":"Alice Updated","age":26}'

# 删除用户
curl -X DELETE http://localhost:3000/users/1

六、状态码处理 #

6.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("/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"})
})

6.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.StatusBadRequest          // 400
fiber.StatusUnauthorized        // 401
fiber.StatusForbidden           // 403
fiber.StatusNotFound            // 404
fiber.StatusInternalServerError // 500

七、错误处理 #

7.1 基本错误处理 #

go
app.Get("/error", func(c *fiber.Ctx) error {
    return fiber.NewError(400, "Custom error message")
})

app.Get("/error2", func(c *fiber.Ctx) error {
    return c.Status(400).JSON(fiber.Map{
        "error": "Something went wrong",
    })
})

7.2 全局错误处理 #

go
app := fiber.New(fiber.Config{
    ErrorHandler: func(c *fiber.Ctx, err error) error {
        code := fiber.StatusInternalServerError
        if e, ok := err.(*fiber.Error); ok {
            code = e.Code
        }
        return c.Status(code).JSON(fiber.Map{
            "error": err.Error(),
        })
    },
})

八、总结 #

8.1 核心要点 #

要点 说明
创建应用 fiber.New()
定义路由 app.Get()、app.Post()等方法
处理函数 func(c *fiber.Ctx) error
启动服务 app.Listen()
Context 请求上下文,获取参数和响应

8.2 下一步 #

现在你已经创建了第一个Fiber应用,接下来让我们学习 项目结构,组织更复杂的项目!

最后更新:2026-03-28