Ở bài viết trước: Giới thiệu về Fiber Web Framework. Sau đây là 1 số ví dụ sử dụng Fiber Web Framework. Nó sẽ giúp các bạn có cái nhìn tổng quan về Fiber Web Framework.
Chương trình Hello World cơ bản
package main import "github.com/gofiber/fiber/v2" func main() { app := fiber.New() app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World ?!") }) app.Listen(":3000") }
Basic Routing / Định tuyến cơ bản
func main() { app := fiber.New() // GET /john app.Get("/:name", func(c *fiber.Ctx) error { msg := fmt.Sprintf("Hello, %s ?!", c.Params("name")) return c.SendString(msg) // => Hello john ?! }) // GET /john/75 app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error { msg := fmt.Sprintf("? %s is %s years old", c.Params("name"), c.Params("age")) return c.SendString(msg) // => ? john is 75 years old }) // GET /dictionary.txt app.Get("/:file.:ext", func(c *fiber.Ctx) error { msg := fmt.Sprintf("? %s.%s", c.Params("file"), c.Params("ext")) return c.SendString(msg) // => ? dictionary.txt }) // GET /flights/LAX-SFO app.Get("/flights/:from-:to", func(c *fiber.Ctx) error { msg := fmt.Sprintf("? From: %s, To: %s", c.Params("from"), c.Params("to")) return c.SendString(msg) // => ? From: LAX, To: SFO }) // GET /api/register app.Get("/api/*", func(c *fiber.Ctx) error { msg := fmt.Sprintf("✋ %s", c.Params("*")) return c.SendString(msg) // => ✋ register }) log.Fatal(app.Listen(":3000")) }
Serving Static Files / Xử lý file tĩnh
func main() { app := fiber.New() app.Static("/", "./public") // => http://localhost:3000/js/script.js // => http://localhost:3000/css/style.css app.Static("/prefix", "./public") // => http://localhost:3000/prefix/js/script.js // => http://localhost:3000/prefix/css/style.css app.Static("*", "./public/index.html") // => http://localhost:3000/any/path/shows/index/html log.Fatal(app.Listen(":3000")) }
Middleware & Next
func main() { app := fiber.New() // Match any route app.Use(func(c *fiber.Ctx) error { fmt.Println("? First handler") return c.Next() }) // Match all routes starting with /api app.Use("/api", func(c *fiber.Ctx) error { fmt.Println("? Second handler") return c.Next() }) // GET /api/register app.Get("/api/list", func(c *fiber.Ctx) error { fmt.Println("? Last handler") return c.SendString("Hello, World ?!") }) log.Fatal(app.Listen(":3000")) }
Views Template Engines
package main import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/template/pug" ) func main() { // You can setup Views engine before initiation app: app := fiber.New(fiber.Config{ Views: pug.New("./views", ".pug"), }) // And now, you can call template `./views/home.pug` like this: app.Get("/", func(c *fiber.Ctx) error { return c.Render("home", fiber.Map{ "title": "Homepage", "year": 1999, }) }) log.Fatal(app.Listen(":3000")) }
Grouping routes into chains / Nhóm các định tuyển trong chuỗi
func middleware(c *fiber.Ctx) error { fmt.Println("Don't mind me!") return c.Next() } func handler(c *fiber.Ctx) error { return c.SendString(c.Path()) } func main() { app := fiber.New() // Root API route api := app.Group("/api", middleware) // /api // API v1 routes v1 := api.Group("/v1", middleware) // /api/v1 v1.Get("/list", handler) // /api/v1/list v1.Get("/user", handler) // /api/v1/user // API v2 routes v2 := api.Group("/v2", middleware) // /api/v2 v2.Get("/list", handler) // /api/v2/list v2.Get("/user", handler) // /api/v2/user // ... }
Middleware logger
package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" ) func main() { app := fiber.New() app.Use(logger.New()) // ... log.Fatal(app.Listen(":3000")) }
Cross-Origin Resource Sharing (CORS)
import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" ) func main() { app := fiber.New() app.Use(cors.New()) // ... log.Fatal(app.Listen(":3000")) }
Custom 404 response / Tạo phản hồi 404
func main() { app := fiber.New() app.Static("/", "./public") app.Get("/demo", func(c *fiber.Ctx) error { return c.SendString("This is a demo!") }) app.Post("/register", func(c *fiber.Ctx) error { return c.SendString("Welcome!") }) // Last middleware to match anything app.Use(func(c *fiber.Ctx) error { return c.SendStatus(404) // => 404 "Not Found" }) log.Fatal(app.Listen(":3000")) }
JSON Response / Phản hồi JSON
type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { app := fiber.New() app.Get("/user", func(c *fiber.Ctx) error { return c.JSON(&User{"John", 20}) // => {"name":"John", "age":20} }) app.Get("/json", func(c *fiber.Ctx) error { return c.JSON(fiber.Map{ "success": true, "message": "Hi John!", }) // => {"success":true, "message":"Hi John!"} }) log.Fatal(app.Listen(":3000")) }
WebSocket Upgrade / Nâng cấp WebSocket
import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/websocket" ) func main() { app := fiber.New() app.Get("/ws", websocket.New(func(c *websocket.Conn) { for { mt, msg, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", msg) err = c.WriteMessage(mt, msg) if err != nil { log.Println("write:", err) break } } })) log.Fatal(app.Listen(":3000")) // ws://localhost:3000/ws }
Recover middleware / Khôi phục Middleware
import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/recover" ) func main() { app := fiber.New() app.Use(recover.New()) app.Get("/", func(c *fiber.Ctx) error { panic("normally this would crash your app") }) log.Fatal(app.Listen(":3000")) }
Validator package
type Job struct{ Type string `validate:"required,min=3,max=32"` Salary int `validate:"required,number"` } type User struct{ Name string `validate:"required,min=3,max=32"` IsActive bool `validate:"required,eq=True|eq=False"` Email string `validate:"required,email,min=6,max=32"` Job Job `validate:"dive"` } type ErrorResponse struct { FailedField string Tag string Value string } func ValidateStruct(user User) []*ErrorResponse { var errors []*ErrorResponse validate := validator.New() err := validate.Struct(user) if err != nil { for _, err := range err.(validator.ValidationErrors) { var element ErrorResponse element.FailedField = err.StructNamespace() element.Tag = err.Tag() element.Value = err.Param() errors = append(errors, &element) } } return errors } func AddUser(c *fiber.Ctx) { //Connect to database user := new(User) if err := c.BodyParser(user); err != nil { errors := ValidateStruct(*user) if errors != nil { c.JSON(errors) return } } //Do something else here //Return user c.JSON(user) } // Running a test with the following curl commands // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"isactive\":\"True\"}" http://localhost:8080/register/user // Results in // [{"FailedField":"User.Email","Tag":"required","Value":""},{"FailedField":"User.Job.Salary","Tag":"required","Value":""},{"FailedField":"User.Job.Type","Tag":"required","Value":""}]⏎
Catching Errors / Bắt lỗi
app.Get("/", func(c *fiber.Ctx) error { // Pass error to Fiber return c.SendFile("file-does-not-exist") })
Các bạn có tham khảo nhiều ví dụ, ứng dụng của Fiber Web Framework ở đây
Nguồn: vinasupport.com