(原) Fiber 又一个Golang框架 例

原创文章,请后转载,并注明出处。

i18n

package main

import (
	"log"
	"strconv"

	"github.com/BurntSushi/toml"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/template/html"
	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	// 使用默认语言(英语)创建新的语言包。
	bundle := i18n.NewBundle(language.English)

	// 注册toml unmarshal函数。
	bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)

	// 加载其他语言的翻译。
	// 由于我们提供了默认的翻译,因此不需要加载active.en.toml。
	bundle.MustLoadMessageFile("./lang/active.es.toml")
	bundle.MustLoadMessageFile("./lang/active.ru.toml")
	bundle.MustLoadMessageFile("./lang/active.zh.toml")

	// 通过使用<engine>.new(dir,ext string)传递模板文件夹和模板扩展来创建新引擎
	engine := html.New("./templates", ".html")

	// 在每次渲染时重新加载模板,有利于开发
	engine.Reload(true) // Optional. Default: false

    // 创建引擎后,可以将其传递给Fiber的视图引擎
	app := fiber.New(fiber.Config{
		Views: engine,
	})

	// 渲染模板.
	app.Get("/", func(c *fiber.Ctx) error {
		lang := c.Query("lang")            // 从查询中分析语言
		accept := c.Get("Accept-Language") // 或者,从头解析语言

		// 创建新的定位器
		localizer := i18n.NewLocalizer(bundle, lang, accept)

		// 设置默认用户名(示例)
		name := c.Query("name")
		if name == "" {
			name = "Bob"
		}

		// 设置标题消息.
		helloPerson := localizer.MustLocalize(&i18n.LocalizeConfig{
			DefaultMessage: &i18n.Message{
				ID:    "HelloPerson",
				Other: "Hello {{.Name}}",
			},
			TemplateData: map[string]string{
				"Name": name,
			},
		})

		// 分析并设置未读邮件数
		unreadEmailCount, _ := strconv.ParseInt(c.Query("unread"), 10, 64)

		myUnreadEmails := localizer.MustLocalize(&i18n.LocalizeConfig{
			DefaultMessage: &i18n.Message{
				ID:          "MyUnreadEmails",
				Description: "The number of unread emails I have",
				One:         "I have {{.PluralCount}} unread email.",
				Other:       "I have {{.PluralCount}} unread emails.",
			},
			PluralCount: unreadEmailCount,
		})

		personUnreadEmails := localizer.MustLocalize(&i18n.LocalizeConfig{
			DefaultMessage: &i18n.Message{
				ID:          "PersonUnreadEmails",
				Description: "The number of unread emails a person has",
				One:         "{{.Name}} has {{.UnreadEmailCount}} unread email.",
				Other:       "{{.Name}} has {{.UnreadEmailCount}} unread emails.",
			},
			PluralCount: unreadEmailCount,
			TemplateData: map[string]interface{}{
				"Name":             name,
				"UnreadEmailCount": unreadEmailCount,
			},
		})

		// 返回呈现模板.
		return c.Render("index", fiber.Map{
			"Title": helloPerson,
			"Paragraphs": []string{
				myUnreadEmails,
				personUnreadEmails,
			},
		})
	})

	log.Fatal(app.Listen(":3000"))
}

文件上传

package main

import (
	"fmt"
	"log"

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

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

	app.Post("/", func(c *fiber.Ctx) error {
		// 从表单字段“document”获取第一个文件:
		file, err := c.FormFile("document")
		if err != nil {
			return err
		}
		return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
	})

	log.Fatal(app.Listen(":3000"))
}
package main

import (
	"fmt"
	"log"

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

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

	app.Post("/", func(c *fiber.Ctx) error {
		// 解析多部分表单:
		form, err := c.MultipartForm()
		if err != nil {
			return err
		}
		// => *multipart.Form

        // 从“documents”键获取所有文件
		files := form.File["documents"]
		// => []*multipart.FileHeader

		// 循环浏览文件 :
		for _, file := range files {
			fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
			// => "tutorial.pdf" 360641 "application/pdf"

			err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))

			if err != nil {
				return err
			}
		}
		return nil
	})

	log.Fatal(app.Listen(":3000"))
}

websocket

package main

import (
	"fmt"
	"log"

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

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

	// Optional middleware
	app.Use("/ws", func(c *fiber.Ctx) error {
		if c.Get("host") == "localhost:3000" {
			c.Locals("Host", "Localhost:3000")
			return c.Next()
		}
		return c.Status(403).SendString("Request origin not allowed")
	})

	// Upgraded websocket request
	app.Get("/ws", websocket.New(func(c *websocket.Conn) {
		fmt.Println(c.Locals("Host")) // "Localhost:3000"
		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
			}
		}
	}))

	// ws://localhost:3000/ws
	log.Fatal(app.Listen(":3000"))
}

相关文章