Перейти к основному содержимому

Первая программа на Fiber

Разработчику Архитектору

Первая программа на Fiber

Fiber — быстрый фреймворк на базе fasthttp (не совместим с net/http.Handler). API напоминает Express.js.

Обзор и trade-offs: Фреймворки Go · Gin · Echo.


Инициализация

mkdir fiber-notes && cd fiber-notes
go mod init example.com/fiber-notes
go get github.com/gofiber/fiber/v2

REST API «Заметки»

main.go:

package main

import (
"strconv"
"sync"

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

type Note struct {
ID int `json:"id"`
Text string `json:"text"`
}

type NoteCreate struct {
Text string `json:"text"`
}

var (
notes []Note
nextID = 1
mu sync.Mutex
)

func main() {
app := fiber.New()

app.Get("/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"status": "ok"})
})

api := app.Group("/api")
api.Get("/notes", listNotes)
api.Post("/notes", createNote)
api.Delete("/notes/:id", deleteNote)

app.Listen(":3000")
}

func listNotes(c *fiber.Ctx) error {
mu.Lock()
defer mu.Unlock()
return c.JSON(notes)
}

func createNote(c *fiber.Ctx) error {
var body NoteCreate
if err := c.BodyParser(&body); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
}
if body.Text == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "text required"})
}
mu.Lock()
note := Note{ID: nextID, Text: body.Text}
nextID++
notes = append(notes, note)
mu.Unlock()
return c.Status(fiber.StatusCreated).JSON(note)
}

func deleteNote(c *fiber.Ctx) error {
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid id"})
}
mu.Lock()
defer mu.Unlock()
for i, n := range notes {
if n.ID == id {
notes = append(notes[:i], notes[i+1:]...)
return c.SendStatus(fiber.StatusNoContent)
}
}
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "not found"})
}
go run .

Порт по умолчанию в примере: 3000 (типично для Fiber).


Проверка

curl http://127.0.0.1:3000/health
curl -X POST http://127.0.0.1:3000/api/notes \
-H "Content-Type: application/json" \
-d '{"text":"Изучить Fiber"}'

Важно помнить

  • Нельзя вставить Fiber в существующий http.ServeMux без адаптера;
  • HTTP/2 напрямую не поддерживается — часто ставят nginx/envoy перед сервисом;
  • для библиотек, завязанных на net/http, предпочтите Echo или Gin.

Дальше


См. также

Другие статьи этого же раздела в боковом меню (как на странице «О разделе»).