├── .github
├── CNAME
├── .gitpod.yml
├── PULL_REQUEST_TEMPLATE
│ └── pull_request_template.md
├── .editorconfig
├── ISSUE_TEMPLATE
│ ├── feature_request.md
│ ├── question.md
│ └── bug_report.md
├── FUNDING.yml
├── workflows
│ ├── security.yml
│ └── go.yml
├── stale.yml
├── config.yml
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── README_zh-CN.md
├── README_ko.md
├── README_ja.md
├── README_tr.md
├── README_pt.md
├── README_fr.md
├── README_es.md
├── README_id.md
└── README.md
├── go.mod
├── .travis.yml
├── LICENSE
├── go.sum
├── app_test.go
├── router.go
└── app.go
/.github/CNAME:
--------------------------------------------------------------------------------
1 | fiber.wiki
--------------------------------------------------------------------------------
/.github/.gitpod.yml:
--------------------------------------------------------------------------------
1 | tasks:
2 | - init: go get && go build ./... && go test ./...
3 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md:
--------------------------------------------------------------------------------
1 | **Fixes issue:** #
2 |
3 | **Changes proposed in this pull request:**
4 |
5 | -
6 | -
7 | -
8 |
9 | **Additional context:**
10 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/gofiber/fiber
2 |
3 | go 1.11
4 |
5 | require (
6 | github.com/gorilla/schema v1.1.0
7 | github.com/json-iterator/go v1.1.9
8 | github.com/valyala/fasthttp v1.9.0
9 | )
10 |
--------------------------------------------------------------------------------
/.github/.editorconfig:
--------------------------------------------------------------------------------
1 | root = false
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | charset = utf-8
7 | max_line_length = 100
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 |
11 | [{*.mod,*.sum,*.go}]
12 | indent_style = tab
13 | indent_size = 4
14 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: "🔥 "
5 | labels: enhancement
6 | assignees: ""
7 | ---
8 |
9 | **Is your feature request related to a problem?**
10 |
11 | **Describe the solution you'd like**
12 |
13 | **Describe alternatives you've considered**
14 |
15 | **Additional context**
16 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/question.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Question
3 | about: Ask a question so we can help
4 | title: "🤔 "
5 | labels: question
6 | assignees: ""
7 | ---
8 | **Question description**
9 |
10 | **Code snippet (optional)**
11 |
12 | ```go
13 | package main
14 |
15 | import "github.com/gofiber/fiber"
16 |
17 | func main() {
18 | app := fiber.New()
19 | // ..
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 | dist: xenial
3 |
4 | os:
5 | - linux
6 | - windows
7 | - osx
8 |
9 | go:
10 | - 1.11.x
11 | - 1.12.x
12 | - 1.13.x
13 | - 1.14.x
14 |
15 | env:
16 | - GO111MODULE=on
17 |
18 | script:
19 | - GOOS=linux go build
20 | - GOOS=darwin go build
21 | - GOOS=freebsd go build
22 | - GOOS=windows go build
23 | - GOARCH=386 go build
24 |
25 | - go test -v
26 | - go test -race -v
27 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | custom: https://www.buymeacoffee.com/fenny
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: "🐞 "
5 | labels: bug
6 | assignees: ""
7 | ---
8 | **Fiber version/commit**
9 |
10 | **Issue description**
11 |
12 | **Expected behavior**
13 |
14 | **Steps to reproduce**
15 |
16 | **Code snippet**
17 |
18 | ```go
19 | package main
20 |
21 | import "github.com/gofiber/fiber"
22 |
23 | func main() {
24 | app := fiber.New()
25 | // ..
26 | }
27 | ```
28 |
--------------------------------------------------------------------------------
/.github/workflows/security.yml:
--------------------------------------------------------------------------------
1 | on: [push]
2 | name: Security
3 | jobs:
4 | test:
5 | strategy:
6 | matrix:
7 | go-version: [1.13.x]
8 | platform: [ubuntu-latest]
9 | runs-on: ${{ matrix.platform }}
10 | steps:
11 | - name: Install Go
12 | uses: actions/setup-go@v1
13 | with:
14 | go-version: ${{ matrix.go-version }}
15 | - name: Checkout code
16 | uses: actions/checkout@v2
17 | - name: Security
18 | run: go get github.com/securego/gosec/cmd/gosec; `go env GOPATH`/bin/gosec ./...
19 |
--------------------------------------------------------------------------------
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | name: Go
2 | on: [push]
3 | jobs:
4 |
5 | build:
6 | name: Build
7 | runs-on: ubuntu-latest
8 | steps:
9 |
10 | - name: Set up Go 1.13
11 | uses: actions/setup-go@v1
12 | with:
13 | go-version: 1.13
14 | id: go
15 |
16 | - name: Check out code into the Go module directory
17 | uses: actions/checkout@v2
18 |
19 | - name: Get dependencies
20 | run: |
21 | go get -v -t -d ./...
22 | if [ -f Gopkg.toml ]; then
23 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
24 | dep ensure
25 | fi
26 |
27 | - name: Build
28 | run: go build -v .
29 |
--------------------------------------------------------------------------------
/.github/stale.yml:
--------------------------------------------------------------------------------
1 | # Number of days of inactivity before an issue becomes stale
2 | daysUntilStale: 60
3 |
4 | # Number of days of inactivity before a stale issue is closed
5 | daysUntilClose: 7
6 |
7 | # Issues with these labels will never be considered stale
8 | exemptLabels:
9 | - pinned
10 | - security
11 |
12 | # Label to use when marking an issue as stale
13 | staleLabel: wontfix
14 |
15 | # Comment to post when marking an issue as stale. Set to `false` to disable
16 | markComment: >
17 | 👋 Hello. Is this still relevant? If so, what is blocking it? Is there
18 | anything you can do to help move it forward?
19 |
20 | > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
21 |
22 | Thank you for your contributions.
23 |
24 | # Comment to post when closing a stale Issue or Pull Request. Set to `false` to disable
25 | closeComment: >
26 | ⚡️ This issue has been automatically closed because it has not had recent activity.
--------------------------------------------------------------------------------
/.github/config.yml:
--------------------------------------------------------------------------------
1 | # Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome
2 | # Comment to be posted to on first time issues
3 | newIssueWelcomeComment: >
4 | Thanks for opening your first issue here! 🎉 Be sure to follow the issue template!
5 | If you want to chat with us, join ons on Telegram https://t.me/gofiber
6 |
7 | # Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome
8 | # Comment to be posted to on PRs from first time contributors in your repository
9 | newPRWelcomeComment: >
10 | Thanks for opening this pull request! 🎉 Please check out our contributing guidelines.
11 | If you want to chat with us, join ons on Telegram https://t.me/gofiber
12 |
13 | # Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge
14 | # Comment to be posted to on pull requests merged by a first time user
15 | firstPRMergeComment: >
16 | Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you!
17 | If you want to chat with us, join ons on Telegram https://t.me/gofiber
18 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue, [Gitter](https://gitter.im/gofiber/community) or any other method with the owners of this repository before making a change.
4 |
5 | Please note: we have a code of conduct, please follow it in all your interactions with the `Fiber` project.
6 |
7 | ## Pull Request Process
8 |
9 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a build.
10 | 2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters.
11 | 3. Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
12 | 4. You may merge the Pull Request in once you have the sign-off of two other developers or if you do not have permission to do that, you may request the second reviewer to merge it for you.
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019-present Fenny and Fiber Contributors
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
4 | github.com/gorilla/schema v1.1.0 h1:CamqUDOFUBqzrvxuz2vEwo8+SUdwsluFh7IlzJh30LY=
5 | github.com/gorilla/schema v1.1.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU=
6 | github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
7 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
8 | github.com/klauspost/compress v1.8.2 h1:Bx0qjetmNjdFXASH02NSAREKpiaDwkO1DRZ3dV2KCcs=
9 | github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
10 | github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
11 | github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
12 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
13 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
14 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
15 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
17 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
18 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
19 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
20 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
21 | github.com/valyala/fasthttp v1.9.0 h1:hNpmUdy/+ZXYpGy0OBfm7K0UQTzb73W0T0U4iJIVrMw=
22 | github.com/valyala/fasthttp v1.9.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w=
23 | github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
24 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
25 | golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
26 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
27 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
28 |
--------------------------------------------------------------------------------
/app_test.go:
--------------------------------------------------------------------------------
1 | // 🚀 Fiber is an Express inspired web framework written in Go with 💖
2 | // 📌 API Documentation: https://fiber.wiki
3 | // 📝 Github Repository: https://github.com/gofiber/fiber
4 |
5 | package fiber
6 |
7 | import (
8 | "net/http"
9 | "testing"
10 | )
11 |
12 | var handler = func(c *Ctx) {}
13 |
14 | func is200(t *testing.T, app *App, url string, m ...string) {
15 |
16 | method := "GET"
17 | if len(m) > 0 {
18 | method = m[0]
19 | }
20 | req, _ := http.NewRequest(method, url, nil)
21 | resp, err := app.Test(req)
22 | if err != nil {
23 | t.Fatalf("%s - %s - %v", method, url, err)
24 | }
25 | if resp.StatusCode != 200 {
26 | t.Fatalf("%s - %s - %v", method, url, resp.StatusCode)
27 | }
28 | }
29 | func Test_Methods(t *testing.T) {
30 | app := New()
31 |
32 | app.Connect("/:john?/:doe?", handler)
33 | is200(t, app, "/", "CONNECT")
34 |
35 | app.Connect("/:john?/:doe?", handler)
36 | is200(t, app, "/", "CONNECT")
37 |
38 | app.Put("/:john?/:doe?", handler)
39 | is200(t, app, "/", "CONNECT")
40 |
41 | app.Post("/:john?/:doe?", handler)
42 | is200(t, app, "/", "POST")
43 |
44 | app.Delete("/:john?/:doe?", handler)
45 | is200(t, app, "/", "DELETE")
46 |
47 | app.Head("/:john?/:doe?", handler)
48 | is200(t, app, "/", "HEAD")
49 |
50 | app.Patch("/:john?/:doe?", handler)
51 | is200(t, app, "/", "PATCH")
52 |
53 | app.Options("/:john?/:doe?", handler)
54 | is200(t, app, "/", "OPTIONS")
55 |
56 | app.Trace("/:john?/:doe?", handler)
57 | is200(t, app, "/", "TRACE")
58 |
59 | app.Get("/:john?/:doe?", handler)
60 | is200(t, app, "/", "GET")
61 |
62 | app.All("/:john?/:doe?", handler)
63 | is200(t, app, "/", "POST")
64 |
65 | app.Use("/:john?/:doe?", handler)
66 | is200(t, app, "/", "GET")
67 |
68 | }
69 |
70 | func Test_Static(t *testing.T) {
71 | app := New()
72 | grp := app.Group("/v1")
73 | grp.Static("/v2", ".travis.yml")
74 | app.Static("/*", ".github/FUNDING.yml")
75 | app.Static("/john", "./.github")
76 | req, _ := http.NewRequest("GET", "/john/stale.yml", nil)
77 | resp, err := app.Test(req)
78 | if err != nil {
79 | t.Fatalf(`%s: %s`, t.Name(), err)
80 | }
81 | if resp.StatusCode != 200 {
82 | t.Fatalf(`%s: StatusCode %v`, t.Name(), resp.StatusCode)
83 | }
84 | if resp.Header.Get("Content-Length") == "" {
85 | t.Fatalf(`%s: Missing Content-Length`, t.Name())
86 | }
87 | req, _ = http.NewRequest("GET", "/yesyes/john/doe", nil)
88 | resp, err = app.Test(req)
89 | if err != nil {
90 | t.Fatalf(`%s: %s`, t.Name(), err)
91 | }
92 | if resp.StatusCode != 200 {
93 | t.Fatalf(`%s: StatusCode %v`, t.Name(), resp.StatusCode)
94 | }
95 | if resp.Header.Get("Content-Length") == "" {
96 | t.Fatalf(`%s: Missing Content-Length`, t.Name())
97 | }
98 | req, _ = http.NewRequest("GET", "/john/stale.yml", nil)
99 | resp, err = app.Test(req)
100 | if err != nil {
101 | t.Fatalf(`%s: %s`, t.Name(), err)
102 | }
103 | if resp.StatusCode != 200 {
104 | t.Fatalf(`%s: StatusCode %v`, t.Name(), resp.StatusCode)
105 | }
106 | if resp.Header.Get("Content-Length") == "" {
107 | t.Fatalf(`%s: Missing Content-Length`, t.Name())
108 | }
109 | req, _ = http.NewRequest("GET", "/v1/v2", nil)
110 | resp, err = app.Test(req)
111 | if err != nil {
112 | t.Fatalf(`%s: %s`, t.Name(), err)
113 | }
114 | if resp.StatusCode != 200 {
115 | t.Fatalf(`%s: StatusCode %v`, t.Name(), resp.StatusCode)
116 | }
117 | if resp.Header.Get("Content-Length") == "" {
118 | t.Fatalf(`%s: Missing Content-Length`, t.Name())
119 | }
120 | }
121 |
122 | func Test_Group(t *testing.T) {
123 | app := New()
124 |
125 | grp := app.Group("/test")
126 | grp.Get("/", handler)
127 | is200(t, app, "/test", "GET")
128 |
129 | grp.Get("/:demo?", handler)
130 | is200(t, app, "/test/john", "GET")
131 |
132 | grp.Connect("/CONNECT", handler)
133 | is200(t, app, "/test/CONNECT", "CONNECT")
134 |
135 | grp.Put("/PUT", handler)
136 | is200(t, app, "/test/PUT", "PUT")
137 |
138 | grp.Post("/POST", handler)
139 | is200(t, app, "/test/POST", "POST")
140 |
141 | grp.Delete("/DELETE", handler)
142 | is200(t, app, "/test/DELETE", "DELETE")
143 |
144 | grp.Head("/HEAD", handler)
145 | is200(t, app, "/test/HEAD", "HEAD")
146 |
147 | grp.Patch("/PATCH", handler)
148 | is200(t, app, "/test/PATCH", "PATCH")
149 |
150 | grp.Options("/OPTIONS", handler)
151 | is200(t, app, "/test/OPTIONS", "OPTIONS")
152 |
153 | grp.Trace("/TRACE", handler)
154 | is200(t, app, "/test/TRACE", "TRACE")
155 |
156 | grp.All("/ALL", handler)
157 | is200(t, app, "/test/ALL", "POST")
158 |
159 | grp.Use("/USE", handler)
160 | is200(t, app, "/test/USE/oke", "GET")
161 |
162 | api := grp.Group("/v1")
163 | api.Post("/", handler)
164 | is200(t, app, "/test/v1/", "POST")
165 |
166 | api.Get("/users", handler)
167 | is200(t, app, "/test/v1/users", "GET")
168 | }
169 |
170 | // func Test_Listen(t *testing.T) {
171 | // t.Parallel()
172 | // app := New()
173 | // app.Banner = false
174 | // go func() {
175 | // time.Sleep(1 * time.Second)
176 | // _ = app.Shutdown()
177 | // }()
178 | // app.Listen(3002)
179 | // go func() {
180 | // time.Sleep(1 * time.Second)
181 | // _ = app.Shutdown()
182 | // }()
183 | // app.Listen("3002")
184 | // }
185 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8 |
9 | ## Our Standards
10 |
11 | Examples of behavior that contributes to a positive environment for our community include:
12 |
13 | - Demonstrating empathy and kindness toward other people
14 | - Being respectful of differing opinions, viewpoints, and experiences
15 | - Giving and gracefully accepting constructive feedback
16 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17 | - Focusing on what is best not just for us as individuals, but for the overall community
18 |
19 | Examples of unacceptable behavior include:
20 |
21 | - The use of sexualized language or imagery, and sexual attention or advances of any kind
22 | - Trolling, insulting or derogatory comments, and personal or political attacks
23 | - Public or private harassment
24 | - Publishing others' private information, such as a physical or email address, without their explicit permission
25 | - Other conduct which could reasonably be considered inappropriate in a professional setting
26 |
27 | ## Enforcement Responsibilities
28 |
29 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
32 |
33 | ## Scope
34 |
35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
36 |
37 | ## Enforcement
38 |
39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [Gitter](https://gitter.im/gofiber/community). All complaints will be reviewed and investigated promptly and fairly.
40 |
41 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
42 |
43 | ## Enforcement Guidelines
44 |
45 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
46 |
47 | ### 1. Correction
48 |
49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
50 |
51 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
52 |
53 | ### 2. Warning
54 |
55 | **Community Impact**: A violation through a single incident or series of actions.
56 |
57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
58 |
59 | ### 3. Temporary Ban
60 |
61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
62 |
63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
64 |
65 | ### 4. Permanent Ban
66 |
67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
68 |
69 | **Consequence**: A permanent ban from any sort of public interaction within the community.
70 |
71 | ## Attribution
72 |
73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
74 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
75 |
76 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
77 |
78 | [homepage]: https://www.contributor-covenant.org
79 |
80 | For answers to common questions about this code of conduct, see the FAQ at
81 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
82 |
--------------------------------------------------------------------------------
/router.go:
--------------------------------------------------------------------------------
1 | // 🚀 Fiber is an Express inspired web framework written in Go with 💖
2 | // 📌 API Documentation: https://fiber.wiki
3 | // 📝 Github Repository: https://github.com/gofiber/fiber
4 |
5 | package fiber
6 |
7 | import (
8 | "log"
9 | "regexp"
10 | "strings"
11 | "time"
12 |
13 | fasthttp "github.com/valyala/fasthttp"
14 | )
15 |
16 | // Route struct
17 | type Route struct {
18 | isGet bool // allows HEAD requests if GET
19 |
20 | isMiddleware bool // is middleware route
21 |
22 | isStar bool // path == '*'
23 | isSlash bool // path == '/'
24 | isRegex bool // needs regex parsing
25 |
26 | Method string // http method
27 | Path string // orginal path
28 | Params []string // path params
29 | Regexp *regexp.Regexp // regexp matcher
30 |
31 | Handler func(*Ctx) // ctx handler
32 | }
33 |
34 | func (app *App) nextRoute(ctx *Ctx) {
35 | // Keep track of head matches
36 | lenr := len(app.routes) - 1
37 | for ctx.index < lenr {
38 | ctx.index++
39 | route := app.routes[ctx.index]
40 | match, values := route.matchRoute(ctx.method, ctx.path)
41 | if match {
42 | ctx.route = route
43 | ctx.values = values
44 | route.Handler(ctx)
45 | return
46 | }
47 | }
48 | if len(ctx.Fasthttp.Response.Body()) == 0 {
49 | ctx.SendStatus(404)
50 | }
51 | }
52 |
53 | func (r *Route) matchRoute(method, path string) (match bool, values []string) {
54 | // is route middleware? matches all http methods
55 | if r.isMiddleware {
56 | // '*' or '/' means its a valid match
57 | if r.isStar || r.isSlash {
58 | return true, values
59 | }
60 | // if midware path starts with req.path
61 | if strings.HasPrefix(path, r.Path) {
62 | return true, values
63 | }
64 | // middlewares dont support regex so bye!
65 | return false, values
66 | }
67 | // non-middleware route, http method must match!
68 | // the wildcard method is for .All() & .Use() methods
69 | // If route is GET, also match HEAD requests
70 | if r.Method == method || r.Method[0] == '*' || (r.isGet && len(method) == 4 && method == "HEAD") {
71 | // '*' means we match anything
72 | if r.isStar {
73 | return true, values
74 | }
75 | // simple '/' bool, so you avoid unnecessary comparison for long paths
76 | if r.isSlash && path == "/" {
77 | return true, values
78 | }
79 | // does this route need regex matching?
80 | // does req.path match regex pattern?
81 | if r.isRegex && r.Regexp.MatchString(path) {
82 | // do we have parameters
83 | if len(r.Params) > 0 {
84 | // get values for parameters
85 | matches := r.Regexp.FindAllStringSubmatch(path, -1)
86 | // did we get the values?
87 | if len(matches) > 0 && len(matches[0]) > 1 {
88 | values = matches[0][1:len(matches[0])]
89 | return true, values
90 | }
91 | return false, values
92 | }
93 | return true, values
94 | }
95 | // last thing to do is to check for a simple path match
96 | if len(r.Path) == len(path) && r.Path == path {
97 | return true, values
98 | }
99 | }
100 | // Nothing match
101 | return false, values
102 | }
103 |
104 | func (app *App) handler(fctx *fasthttp.RequestCtx) {
105 | // get fiber context from sync pool
106 | ctx := acquireCtx(fctx)
107 | defer releaseCtx(ctx)
108 | // attach app poiner and compress settings
109 | ctx.app = app
110 |
111 | // Case sensitive routing
112 | if !app.Settings.CaseSensitive {
113 | ctx.path = strings.ToLower(ctx.path)
114 | }
115 | // Strict routing
116 | if !app.Settings.StrictRouting && len(ctx.path) > 1 {
117 | ctx.path = strings.TrimRight(ctx.path, "/")
118 | }
119 | // Find route
120 | app.nextRoute(ctx)
121 | }
122 |
123 | func (app *App) registerMethod(method, path string, handlers ...func(*Ctx)) {
124 | // Route requires atleast one handler
125 | if len(handlers) == 0 {
126 | log.Fatalf("Missing handler in route")
127 | }
128 | // Cannot have an empty path
129 | if path == "" {
130 | path = "/"
131 | }
132 | // Path always start with a '/' or '*'
133 | if path[0] != '/' && path[0] != '*' {
134 | path = "/" + path
135 | }
136 | // Store original path to strip case sensitive params
137 | original := path
138 | // Case sensitive routing, all to lowercase
139 | if !app.Settings.CaseSensitive {
140 | path = strings.ToLower(path)
141 | }
142 | // Strict routing, remove last `/`
143 | if !app.Settings.StrictRouting && len(path) > 1 {
144 | path = strings.TrimRight(path, "/")
145 | }
146 | // Set route booleans
147 | var isGet = method == "GET"
148 | var isMiddleware = method == "USE"
149 | // Middleware / All allows all HTTP methods
150 | if isMiddleware || method == "ALL" {
151 | method = "*"
152 | }
153 | var isStar = path == "*" || path == "/*"
154 | // Middleware containing only a `/` equals wildcard
155 | if isMiddleware && path == "/" {
156 | isStar = true
157 | }
158 | var isSlash = path == "/"
159 | var isRegex = false
160 | // Route properties
161 | var Params = getParams(original)
162 | var Regexp *regexp.Regexp
163 | // Params requires regex pattern
164 | if len(Params) > 0 {
165 | regex, err := getRegex(path)
166 | if err != nil {
167 | log.Fatal("Router: Invalid path pattern: " + path)
168 | }
169 | isRegex = true
170 | Regexp = regex
171 | }
172 | for i := range handlers {
173 | app.routes = append(app.routes, &Route{
174 | isGet: isGet,
175 | isMiddleware: isMiddleware,
176 | isStar: isStar,
177 | isSlash: isSlash,
178 | isRegex: isRegex,
179 | Method: method,
180 | Path: path,
181 | Params: Params,
182 | Regexp: Regexp,
183 | Handler: handlers[i],
184 | })
185 | }
186 | }
187 |
188 | func (app *App) registerStatic(prefix, root string, config ...Static) {
189 | // Cannot have an empty prefix
190 | if prefix == "" {
191 | prefix = "/"
192 | }
193 | // Prefix always start with a '/' or '*'
194 | if prefix[0] != '/' && prefix[0] != '*' {
195 | prefix = "/" + prefix
196 | }
197 | // Match anything
198 | var wildcard = false
199 | if prefix == "*" || prefix == "/*" {
200 | wildcard = true
201 | prefix = "/"
202 | }
203 | // Case sensitive routing, all to lowercase
204 | if !app.Settings.CaseSensitive {
205 | prefix = strings.ToLower(prefix)
206 | }
207 | // For security we want to restrict to the current work directory.
208 | if len(root) == 0 {
209 | root = "."
210 | }
211 | // Strip trailing slashes from the root path
212 | if len(root) > 0 && root[len(root)-1] == '/' {
213 | root = root[:len(root)-1]
214 | }
215 | // isSlash ?
216 | var isSlash = prefix == "/"
217 | if strings.Contains(prefix, "*") {
218 | wildcard = true
219 | prefix = strings.Split(prefix, "*")[0]
220 | }
221 | var stripper = len(prefix)
222 | if isSlash {
223 | stripper = 0
224 | }
225 | // Fileserver settings
226 | fs := &fasthttp.FS{
227 | Root: root,
228 | GenerateIndexPages: false,
229 | AcceptByteRange: false,
230 | Compress: false,
231 | CompressedFileSuffix: ".fiber.gz",
232 | CacheDuration: 10 * time.Second,
233 | IndexNames: []string{"index.html"},
234 | PathRewrite: fasthttp.NewPathPrefixStripper(stripper),
235 | PathNotFound: func(ctx *fasthttp.RequestCtx) {
236 | ctx.Response.SetStatusCode(404)
237 | ctx.Response.SetBodyString("Not Found")
238 | },
239 | }
240 | // Set config if provided
241 | if len(config) > 0 {
242 | fs.Compress = config[0].Compress
243 | fs.AcceptByteRange = config[0].ByteRange
244 | fs.GenerateIndexPages = config[0].Browse
245 | if config[0].Index != "" {
246 | fs.IndexNames = []string{config[0].Index}
247 | }
248 | }
249 | fileHandler := fs.NewRequestHandler()
250 | app.routes = append(app.routes, &Route{
251 | isMiddleware: true,
252 | isSlash: isSlash,
253 | Method: "*",
254 | Path: prefix,
255 | Handler: func(c *Ctx) {
256 | // Only handle GET & HEAD methods
257 | if c.method == "GET" || c.method == "HEAD" {
258 | // Do stuff
259 | if wildcard {
260 | c.Fasthttp.Request.SetRequestURI(prefix)
261 | }
262 | // Serve file
263 | fileHandler(c.Fasthttp)
264 | // End response when file is found
265 | if c.Fasthttp.Response.StatusCode() != 404 {
266 | return
267 | }
268 | // Reset response
269 | c.Fasthttp.Response.Reset()
270 | }
271 | c.Next()
272 | },
273 | })
274 | }
275 |
--------------------------------------------------------------------------------
/app.go:
--------------------------------------------------------------------------------
1 | // 🚀 Fiber is an Express inspired web framework written in Go with 💖
2 | // 📌 API Documentation: https://fiber.wiki
3 | // 📝 Github Repository: https://github.com/gofiber/fiber
4 |
5 | package fiber
6 |
7 | import (
8 | "bufio"
9 | "crypto/tls"
10 | "fmt"
11 | "log"
12 | "net"
13 | "net/http"
14 | "net/http/httputil"
15 | "os"
16 | "os/exec"
17 | "reflect"
18 | "runtime"
19 | "strconv"
20 | "strings"
21 | "time"
22 |
23 | fasthttp "github.com/valyala/fasthttp"
24 | )
25 |
26 | // Version of current package
27 | const Version = "1.8.43"
28 |
29 | // Map is a shortcut for map[string]interface{}
30 | type Map map[string]interface{}
31 |
32 | // App denotes the Fiber application.
33 | type App struct {
34 | server *fasthttp.Server // FastHTTP server
35 | routes []*Route // Route stack
36 | Settings *Settings // Fiber settings
37 | }
38 |
39 | // Settings holds is a struct holding the server settings
40 | type Settings struct {
41 | // This will spawn multiple Go processes listening on the same port
42 | Prefork bool // default: false
43 | // Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different.
44 | StrictRouting bool // default: false
45 | // Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes.
46 | CaseSensitive bool // default: false
47 | // Enables the "Server: value" HTTP header.
48 | ServerHeader string // default: ""
49 | // Enables handler values to be immutable even if you return from handler
50 | Immutable bool // default: false
51 | // Max body size that the server accepts
52 | BodyLimit int // default: 4 * 1024 * 1024
53 | // Folder containing template files
54 | TemplateFolder string // default: ""
55 | // Template engine: html, amber, handlebars , mustache or pug
56 | TemplateEngine func(raw string, bind interface{}) (string, error) // default: nil
57 | // Extension for the template files
58 | TemplateExtension string // default: ""
59 | // The amount of time allowed to read the full request including body.
60 | ReadTimeout time.Duration // default: unlimited
61 | // The maximum duration before timing out writes of the response.
62 | WriteTimeout time.Duration // default: unlimited
63 | // The maximum amount of time to wait for the next request when keep-alive is enabled.
64 | IdleTimeout time.Duration // default: unlimited
65 | }
66 |
67 | // Group struct
68 | type Group struct {
69 | prefix string
70 | app *App
71 | }
72 |
73 | // Global variables
74 | var isPrefork, isChild bool
75 |
76 | // New creates a new Fiber named instance.
77 | // You can pass optional settings when creating a new instance.
78 | func New(settings ...*Settings) *App {
79 | // Parse arguments
80 | for _, v := range os.Args[1:] {
81 | if v == "-prefork" {
82 | isPrefork = true
83 | } else if v == "-child" {
84 | isChild = true
85 | }
86 | }
87 | // Create app
88 | app := new(App)
89 | // Create settings
90 | app.Settings = new(Settings)
91 | // Set default settings
92 | app.Settings.Prefork = isPrefork
93 | app.Settings.BodyLimit = 4 * 1024 * 1024
94 | // If settings exist, set defaults
95 | if len(settings) > 0 {
96 | app.Settings = settings[0] // Set custom settings
97 | if !app.Settings.Prefork { // Default to -prefork flag if false
98 | app.Settings.Prefork = isPrefork
99 | }
100 | if app.Settings.BodyLimit == 0 { // Default MaxRequestBodySize
101 | app.Settings.BodyLimit = 4 * 1024 * 1024
102 | }
103 | if app.Settings.Immutable { // Replace unsafe conversion funcs
104 | getString = getStringImmutable
105 | getBytes = getBytesImmutable
106 | }
107 | }
108 | return app
109 | }
110 |
111 | // Group is used for Routes with common prefix to define a new sub-router with optional middleware.
112 | func (app *App) Group(prefix string, handlers ...func(*Ctx)) *Group {
113 | if len(handlers) > 0 {
114 | app.registerMethod("USE", prefix, handlers...)
115 | }
116 | return &Group{
117 | prefix: prefix,
118 | app: app,
119 | }
120 | }
121 |
122 | // Static struct
123 | type Static struct {
124 | // Transparently compresses responses if set to true
125 | // This works differently than the github.com/gofiber/compression middleware
126 | // The server tries minimizing CPU usage by caching compressed files.
127 | // It adds ".fiber.gz" suffix to the original file name.
128 | // Optional. Default value false
129 | Compress bool
130 | // Enables byte range requests if set to true.
131 | // Optional. Default value false
132 | ByteRange bool
133 | // Enable directory browsing.
134 | // Optional. Default value false.
135 | Browse bool
136 | // Index file for serving a directory.
137 | // Optional. Default value "index.html".
138 | Index string
139 | }
140 |
141 | // Static registers a new route with path prefix to serve static files from the provided root directory.
142 | func (app *App) Static(prefix, root string, config ...Static) *App {
143 | app.registerStatic(prefix, root, config...)
144 | return app
145 | }
146 |
147 | // Use registers a middleware route.
148 | // Middleware matches requests beginning with the provided prefix.
149 | // Providing a prefix is optional, it defaults to "/"
150 | func (app *App) Use(args ...interface{}) *App {
151 | var path = ""
152 | var handlers []func(*Ctx)
153 | for i := 0; i < len(args); i++ {
154 | switch arg := args[i].(type) {
155 | case string:
156 | path = arg
157 | case func(*Ctx):
158 | handlers = append(handlers, arg)
159 | default:
160 | log.Fatalf("Invalid handler: %v", reflect.TypeOf(arg))
161 | }
162 | }
163 | app.registerMethod("USE", path, handlers...)
164 | return app
165 | }
166 |
167 | // Connect : https://fiber.wiki/application#http-methods
168 | func (app *App) Connect(path string, handlers ...func(*Ctx)) *App {
169 | app.registerMethod(MethodConnect, path, handlers...)
170 | return app
171 | }
172 |
173 | // Put : https://fiber.wiki/application#http-methods
174 | func (app *App) Put(path string, handlers ...func(*Ctx)) *App {
175 | app.registerMethod(MethodPut, path, handlers...)
176 | return app
177 | }
178 |
179 | // Post : https://fiber.wiki/application#http-methods
180 | func (app *App) Post(path string, handlers ...func(*Ctx)) *App {
181 | app.registerMethod(MethodPost, path, handlers...)
182 | return app
183 | }
184 |
185 | // Delete : https://fiber.wiki/application#http-methods
186 | func (app *App) Delete(path string, handlers ...func(*Ctx)) *App {
187 | app.registerMethod(MethodDelete, path, handlers...)
188 | return app
189 | }
190 |
191 | // Head : https://fiber.wiki/application#http-methods
192 | func (app *App) Head(path string, handlers ...func(*Ctx)) *App {
193 | app.registerMethod(MethodHead, path, handlers...)
194 | return app
195 | }
196 |
197 | // Patch : https://fiber.wiki/application#http-methods
198 | func (app *App) Patch(path string, handlers ...func(*Ctx)) *App {
199 | app.registerMethod(MethodPatch, path, handlers...)
200 | return app
201 | }
202 |
203 | // Options : https://fiber.wiki/application#http-methods
204 | func (app *App) Options(path string, handlers ...func(*Ctx)) *App {
205 | app.registerMethod(MethodOptions, path, handlers...)
206 | return app
207 | }
208 |
209 | // Trace : https://fiber.wiki/application#http-methods
210 | func (app *App) Trace(path string, handlers ...func(*Ctx)) *App {
211 | app.registerMethod(MethodTrace, path, handlers...)
212 | return app
213 | }
214 |
215 | // Get : https://fiber.wiki/application#http-methods
216 | func (app *App) Get(path string, handlers ...func(*Ctx)) *App {
217 | app.registerMethod(MethodGet, path, handlers...)
218 | return app
219 | }
220 |
221 | // All matches all HTTP methods and complete paths
222 | func (app *App) All(path string, handlers ...func(*Ctx)) *App {
223 | app.registerMethod("ALL", path, handlers...)
224 | return app
225 | }
226 |
227 | // Group is used for Routes with common prefix to define a new sub-router with optional middleware.
228 | func (grp *Group) Group(prefix string, handlers ...func(*Ctx)) *Group {
229 | prefix = groupPaths(grp.prefix, prefix)
230 | if len(handlers) > 0 {
231 | grp.app.registerMethod("USE", prefix, handlers...)
232 | }
233 | return &Group{
234 | prefix: prefix,
235 | app: grp.app,
236 | }
237 | }
238 |
239 | // Static : https://fiber.wiki/application#static
240 | func (grp *Group) Static(prefix, root string, config ...Static) *Group {
241 | prefix = groupPaths(grp.prefix, prefix)
242 | grp.app.registerStatic(prefix, root, config...)
243 | return grp
244 | }
245 |
246 | // Use registers a middleware route.
247 | // Middleware matches requests beginning with the provided prefix.
248 | // Providing a prefix is optional, it defaults to "/"
249 | func (grp *Group) Use(args ...interface{}) *Group {
250 | var path = ""
251 | var handlers []func(*Ctx)
252 | for i := 0; i < len(args); i++ {
253 | switch arg := args[i].(type) {
254 | case string:
255 | path = arg
256 | case func(*Ctx):
257 | handlers = append(handlers, arg)
258 | default:
259 | log.Fatalf("Invalid Use() arguments, must be (prefix, handler) or (handler)")
260 | }
261 | }
262 | grp.app.registerMethod("USE", groupPaths(grp.prefix, path), handlers...)
263 | return grp
264 | }
265 |
266 | // Connect : https://fiber.wiki/application#http-methods
267 | func (grp *Group) Connect(path string, handlers ...func(*Ctx)) *Group {
268 | grp.app.registerMethod(MethodConnect, groupPaths(grp.prefix, path), handlers...)
269 | return grp
270 | }
271 |
272 | // Put : https://fiber.wiki/application#http-methods
273 | func (grp *Group) Put(path string, handlers ...func(*Ctx)) *Group {
274 | grp.app.registerMethod(MethodPut, groupPaths(grp.prefix, path), handlers...)
275 | return grp
276 | }
277 |
278 | // Post : https://fiber.wiki/application#http-methods
279 | func (grp *Group) Post(path string, handlers ...func(*Ctx)) *Group {
280 | grp.app.registerMethod(MethodPost, groupPaths(grp.prefix, path), handlers...)
281 | return grp
282 | }
283 |
284 | // Delete : https://fiber.wiki/application#http-methods
285 | func (grp *Group) Delete(path string, handlers ...func(*Ctx)) *Group {
286 | grp.app.registerMethod(MethodDelete, groupPaths(grp.prefix, path), handlers...)
287 | return grp
288 | }
289 |
290 | // Head : https://fiber.wiki/application#http-methods
291 | func (grp *Group) Head(path string, handlers ...func(*Ctx)) *Group {
292 | grp.app.registerMethod(MethodHead, groupPaths(grp.prefix, path), handlers...)
293 | return grp
294 | }
295 |
296 | // Patch : https://fiber.wiki/application#http-methods
297 | func (grp *Group) Patch(path string, handlers ...func(*Ctx)) *Group {
298 | grp.app.registerMethod(MethodPatch, groupPaths(grp.prefix, path), handlers...)
299 | return grp
300 | }
301 |
302 | // Options : https://fiber.wiki/application#http-methods
303 | func (grp *Group) Options(path string, handlers ...func(*Ctx)) *Group {
304 | grp.app.registerMethod(MethodOptions, groupPaths(grp.prefix, path), handlers...)
305 | return grp
306 | }
307 |
308 | // Trace : https://fiber.wiki/application#http-methods
309 | func (grp *Group) Trace(path string, handlers ...func(*Ctx)) *Group {
310 | grp.app.registerMethod(MethodTrace, groupPaths(grp.prefix, path), handlers...)
311 | return grp
312 | }
313 |
314 | // Get : https://fiber.wiki/application#http-methods
315 | func (grp *Group) Get(path string, handlers ...func(*Ctx)) *Group {
316 | grp.app.registerMethod(MethodGet, groupPaths(grp.prefix, path), handlers...)
317 | return grp
318 | }
319 |
320 | // All matches all HTTP methods and complete paths
321 | func (grp *Group) All(path string, handlers ...func(*Ctx)) *Group {
322 | grp.app.registerMethod("ALL", groupPaths(grp.prefix, path), handlers...)
323 | return grp
324 | }
325 |
326 | // Listen serves HTTP requests from the given addr or port.
327 | // You can pass an optional *tls.Config to enable TLS.
328 | func (app *App) Listen(address interface{}, tlsconfig ...*tls.Config) error {
329 | addr, ok := address.(string)
330 | if !ok {
331 | port, ok := address.(int)
332 | if !ok {
333 | return fmt.Errorf("Listen: Host must be an INT port or STRING address")
334 | }
335 | addr = strconv.Itoa(port)
336 | }
337 | if !strings.Contains(addr, ":") {
338 | addr = ":" + addr
339 | }
340 | // Create fasthttp server
341 | app.server = app.newServer()
342 | // Print listening message
343 | if !isChild {
344 | fmt.Printf("Fiber v%s listening on %s\n", Version, addr)
345 | }
346 | var ln net.Listener
347 | var err error
348 | // Prefork enabled
349 | if app.Settings.Prefork && runtime.NumCPU() > 1 {
350 | if ln, err = app.prefork(addr); err != nil {
351 | return err
352 | }
353 | } else {
354 | if ln, err = net.Listen("tcp4", addr); err != nil {
355 | return err
356 | }
357 | }
358 |
359 | // TLS config
360 | if len(tlsconfig) > 0 {
361 | ln = tls.NewListener(ln, tlsconfig[0])
362 | }
363 | return app.server.Serve(ln)
364 | }
365 |
366 | // Shutdown gracefully shuts down the server without interrupting any active connections.
367 | // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
368 | //
369 | // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
370 | // Make sure the program doesn't exit and waits instead for Shutdown to return.
371 | //
372 | // Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
373 | func (app *App) Shutdown() error {
374 | if app.server == nil {
375 | return fmt.Errorf("Server is not running")
376 | }
377 | return app.server.Shutdown()
378 | }
379 |
380 | // Test is used for internal debugging by passing a *http.Request.
381 | // Timeout is optional and defaults to 200ms, -1 will disable it completely.
382 | func (app *App) Test(request *http.Request, msTimeout ...int) (*http.Response, error) {
383 | timeout := 200
384 | if len(msTimeout) > 0 {
385 | timeout = msTimeout[0]
386 | }
387 | if timeout < 0 {
388 | timeout = 60000 // 1 minute
389 | }
390 | // Dump raw http request
391 | dump, err := httputil.DumpRequest(request, true)
392 | if err != nil {
393 | return nil, err
394 | }
395 | // Setup server
396 | app.server = app.newServer()
397 | // Create conn
398 | conn := new(testConn)
399 | // Write raw http request
400 | if _, err = conn.r.Write(dump); err != nil {
401 | return nil, err
402 | }
403 | // Serve conn to server
404 | channel := make(chan error)
405 | go func() {
406 | channel <- app.server.ServeConn(conn)
407 | }()
408 | // Wait for callback
409 | select {
410 | case err := <-channel:
411 | if err != nil {
412 | return nil, err
413 | }
414 | case <-time.After(time.Duration(timeout) * time.Millisecond):
415 | return nil, fmt.Errorf("Timeout error")
416 | }
417 | // Read response
418 | buffer := bufio.NewReader(&conn.w)
419 | // Convert raw http response to *http.Response
420 | resp, err := http.ReadResponse(buffer, request)
421 | if err != nil {
422 | return nil, err
423 | }
424 | // Return *http.Response
425 | return resp, nil
426 | }
427 |
428 | // Sharding: https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
429 | func (app *App) prefork(address string) (ln net.Listener, err error) {
430 | // Master proc
431 | if !isChild {
432 | addr, err := net.ResolveTCPAddr("tcp", address)
433 | if err != nil {
434 | return ln, err
435 | }
436 | tcplistener, err := net.ListenTCP("tcp", addr)
437 | if err != nil {
438 | return ln, err
439 | }
440 | fl, err := tcplistener.File()
441 | if err != nil {
442 | return ln, err
443 | }
444 | files := []*os.File{fl}
445 | childs := make([]*exec.Cmd, runtime.NumCPU()/2)
446 | // #nosec G204
447 | for i := range childs {
448 | childs[i] = exec.Command(os.Args[0], append(os.Args[1:], "-prefork", "-child")...)
449 | childs[i].Stdout = os.Stdout
450 | childs[i].Stderr = os.Stderr
451 | childs[i].ExtraFiles = files
452 | if err := childs[i].Start(); err != nil {
453 | return ln, err
454 | }
455 | }
456 |
457 | for _, child := range childs {
458 | if err := child.Wait(); err != nil {
459 | return ln, err
460 | }
461 | }
462 | os.Exit(0)
463 | } else {
464 | // 1 core per child
465 | runtime.GOMAXPROCS(1)
466 | ln, err = net.FileListener(os.NewFile(3, ""))
467 | }
468 | return ln, err
469 | }
470 |
471 | type disableLogger struct{}
472 |
473 | func (dl *disableLogger) Printf(format string, args ...interface{}) {
474 | // fmt.Println(fmt.Sprintf(format, args...))
475 | }
476 |
477 | func (app *App) newServer() *fasthttp.Server {
478 | return &fasthttp.Server{
479 | Handler: app.handler,
480 | Name: app.Settings.ServerHeader,
481 | MaxRequestBodySize: app.Settings.BodyLimit,
482 | NoDefaultServerHeader: app.Settings.ServerHeader == "",
483 | ReadTimeout: app.Settings.ReadTimeout,
484 | WriteTimeout: app.Settings.WriteTimeout,
485 | IdleTimeout: app.Settings.IdleTimeout,
486 | Logger: &disableLogger{},
487 | LogAllErrors: false,
488 | ErrorHandler: func(ctx *fasthttp.RequestCtx, err error) {
489 | if err.Error() == "body size exceeds the given limit" {
490 | ctx.Response.SetStatusCode(413)
491 | ctx.Response.SetBodyString("Request Entity Too Large")
492 | } else {
493 | ctx.Response.SetStatusCode(400)
494 | ctx.Response.SetBodyString("Bad Request")
495 | }
496 | },
497 | }
498 | }
499 |
--------------------------------------------------------------------------------
/.github/README_zh-CN.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Fiber是一个基于Express的 Web框架,建立在Go语言写的 最快的FasthttpHTTP引擎的基础上。皆在简化 零内存分配和提高性能,以便快速开发。
70 |
71 |
72 | ## ⚡️ 快速入门
73 |
74 | ```go
75 | package main
76 |
77 | import "github.com/gofiber/fiber"
78 |
79 | func main() {
80 | app := fiber.New()
81 |
82 | app.Get("/", func(c *fiber.Ctx) {
83 | c.Send("Hello, World!")
84 | })
85 |
86 | app.Listen(3000)
87 | }
88 | ```
89 |
90 | ## ⚙️ 安装
91 |
92 | 首先, [下载](https://golang.org/dl/)并安装Go。 `1.11`或更高。
93 |
94 | 使用[`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them)命令完成安装:
95 |
96 | ```bash
97 | export GO111MODULE=on
98 | export GOPROXY=https://goproxy.cn
99 |
100 | go get -u github.com/gofiber/fiber
101 | ```
102 |
103 | ## 🤖 性能
104 |
105 | 这些测试由[TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks)和[Go Web执行](https://github.com/smallnest/go-web-framework-benchmark) 。如果要查看所有结果,请访问我们的[Wiki](https://fiber.wiki/benchmarks) 。
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 特点
113 |
114 | - 强大的[路由](https://fiber.wiki/routing)
115 | - [静态文件](https://fiber.wiki/application#static)服务
116 | - 极限[表现](https://fiber.wiki/benchmarks)
117 | - [内存占用低](https://fiber.wiki/benchmarks)
118 | - Express [API端点](https://fiber.wiki/context)
119 | - 中间件和[Next](https://fiber.wiki/context#next)支持
120 | - [快速的](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497)服务器端编程
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - 以及更多[文档](https://fiber.wiki/)
126 |
127 | ## 💡 哲学
128 |
129 | 从[Node.js](https://nodejs.org/en/about/)切换到[Go的](https://golang.org/doc/)新gopher在开始构建Web应用程序或微服务之前正在应对学习过程。 Fiber作为一个**Web框架** ,是按照**极简主义**的思想并遵循**UNIX方式创建的**,因此新的gopher可以以热烈和可信赖的欢迎**方式**迅速进入Go的世界。
130 |
131 | Fiber **受** Internet上最流行的Web框架Expressjs的**启发** 。我们结合了Express的**易用**性和Go的**原始性能** 。如果您曾经在Node.js上实现过Web应用程序(*使用Express.js或类似工具*),那么许多方法和原理对您来说似乎**非常易懂**。
132 |
133 | ## 👀 示例
134 |
135 | 下面列出了一些常见示例。如果您想查看更多代码示例,请访问我们的[Recipes存储库](https://github.com/gofiber/recipes)或访问我们的[API文档](https://fiber.wiki) 。
136 |
137 | ### Routing
138 |
139 | 📖 https://fiber.wiki/#basic-routing
140 |
141 |
142 | ```go
143 | func main() {
144 | app := fiber.New()
145 |
146 | // GET /john
147 | app.Get("/:name", func(c *fiber.Ctx) {
148 | fmt.Printf("Hello %s!", c.Params("name"))
149 | // => Hello john!
150 | })
151 |
152 | // GET /john
153 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
154 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
155 | // => Name: john, Age:
156 | })
157 |
158 | // GET /api/register
159 | app.Get("/api*", func(c *fiber.Ctx) {
160 | fmt.Printf("/api%s", c.Params("*"))
161 | // => /api/register
162 | })
163 |
164 | app.Listen(3000)
165 | }
166 | ```
167 |
168 | ### Serve static files
169 |
170 | 📖 https://fiber.wiki/application#static
171 |
172 | ```go
173 | func main() {
174 | app := fiber.New()
175 |
176 | app.Static("/", "/public")
177 | // => http://localhost:3000/js/script.js
178 | // => http://localhost:3000/css/style.css
179 |
180 | app.Static("/prefix", "/public")
181 | // => http://localhost:3000/prefix/js/script.js
182 | // => http://localhost:3000/prefix/css/style.css
183 |
184 | app.Static("*", "/public/index.html")
185 | // => http://localhost:3000/any/path/shows/index/html
186 |
187 | app.Listen(3000)
188 | }
189 | ```
190 |
191 | ### Middleware & Next
192 |
193 | 📖 https://fiber.wiki/routing#middleware
194 | 📖 https://fiber.wiki/context#next
195 |
196 | ```go
197 | func main() {
198 | app := fiber.New()
199 |
200 | // Match any route
201 | app.Use(func(c *fiber.Ctx) {
202 | fmt.Println("First middleware")
203 | c.Next()
204 | })
205 |
206 | // Match all routes starting with /api
207 | app.Use("/api", func(c *fiber.Ctx) {
208 | fmt.Println("Second middleware")
209 | c.Next()
210 | })
211 |
212 | // GET /api/register
213 | app.Get("/api/list", func(c *fiber.Ctx) {
214 | fmt.Println("Last middleware")
215 | c.Send("Hello, World!")
216 | })
217 |
218 | app.Listen(3000)
219 | }
220 | ```
221 |
222 |
223 | 📚 Show more code examples
224 |
225 | ### Template engines
226 |
227 | 📖 https://fiber.wiki/application#settings
228 | 📖 https://fiber.wiki/context#render
229 | 📖 https://fiber.wiki/middleware#template
230 |
231 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
232 |
233 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
234 |
235 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
236 |
237 | ```go
238 | package main
239 |
240 | import (
241 | "github.com/gofiber/fiber"
242 | "github.com/gofiber/template"
243 | )
244 |
245 | func main() {
246 | // You can setup template engine before initiation app:
247 | app := fiber.New(&fiber.Settings{
248 | TemplateEngine: template.Mustache(),
249 | TemplateFolder: "./views",
250 | TemplateExtension: ".tmpl",
251 | })
252 |
253 | // OR after initiation app at any convenient location:
254 | app.Settings.TemplateEngine = template.Mustache()
255 | app.Settings.TemplateFolder = "./views"
256 | app.Settings.TemplateExtension = ".tmpl"
257 |
258 | // And now, you can call template `./views/home.tmpl` like this:
259 | app.Get("/", func(c *fiber.Ctx) {
260 | c.Render("home", fiber.Map{
261 | "title": "Homepage",
262 | "year": 1999,
263 | })
264 | })
265 |
266 | // ...
267 | }
268 | ```
269 |
270 | ### Grouping routes into chains
271 |
272 | 📖 https://fiber.wiki/application#group
273 |
274 | ```go
275 | func main() {
276 | app := fiber.New()
277 |
278 | // Root API route
279 | api := app.Group("/api", cors()) // /api
280 |
281 | // API v1 routes
282 | v1 := api.Group("/v1", mysql()) // /api/v1
283 | v1.Get("/list", handler) // /api/v1/list
284 | v1.Get("/user", handler) // /api/v1/user
285 |
286 | // API v2 routes
287 | v2 := api.Group("/v2", mongodb()) // /api/v2
288 | v2.Get("/list", handler) // /api/v2/list
289 | v2.Get("/user", handler) // /api/v2/user
290 |
291 | // ...
292 | }
293 | ```
294 |
295 | ### Middleware logger
296 |
297 | 📖 https://fiber.wiki/middleware#logger
298 |
299 | ```go
300 | import (
301 | "github.com/gofiber/fiber"
302 | "github.com/gofiber/logger"
303 | )
304 |
305 | func main() {
306 | app := fiber.New()
307 |
308 | // Optional logger config
309 | config := logger.Config{
310 | Format: "${time} - ${method} ${path}\n",
311 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
312 | }
313 |
314 | // Logger with config
315 | app.Use(logger.New(config))
316 |
317 | app.Listen(3000)
318 | }
319 | ```
320 |
321 | ### Cross-Origin Resource Sharing (CORS)
322 |
323 | 📖 https://fiber.wiki/middleware#cors
324 |
325 | ```go
326 | import (
327 | "github.com/gofiber/fiber"
328 | "github.com/gofiber/cors"
329 | )
330 |
331 | func main() {
332 | app := fiber.New()
333 |
334 | // CORS with default config
335 | app.Use(cors.New())
336 |
337 | app.Listen(3000)
338 | }
339 | ```
340 |
341 | Check CORS by passing any domain in `Origin` header:
342 |
343 | ```bash
344 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
345 | ```
346 |
347 | ### Custom 404 response
348 |
349 | 📖 https://fiber.wiki/application#http-methods
350 |
351 | ```go
352 | func main() {
353 | app := fiber.New()
354 |
355 | app.Static("/public")
356 |
357 | app.Get("/demo", func(c *fiber.Ctx) {
358 | c.Send("This is a demo!")
359 | })
360 |
361 | app.Post("/register", func(c *fiber.Ctx) {
362 | c.Send("Welcome!")
363 | })
364 |
365 | // Last middleware to match anything
366 | app.Use(func(c *fiber.Ctx) {
367 | c.SendStatus(404)
368 | // => 404 "Not Found"
369 | })
370 |
371 | app.Listen(3000)
372 | }
373 | ```
374 |
375 | ### JSON Response
376 |
377 | 📖 https://fiber.wiki/context#json
378 |
379 | ```go
380 | type User struct {
381 | Name string `json:"name"`
382 | Age int `json:"age"`
383 | }
384 |
385 | func main() {
386 | app := fiber.New()
387 |
388 | app.Get("/user", func(c *fiber.Ctx) {
389 | c.JSON(&User{"John", 20})
390 | // => {"name":"John", "age":20}
391 | })
392 |
393 | app.Get("/json", func(c *fiber.Ctx) {
394 | c.JSON(fiber.Map{
395 | "success": true,
396 | "message": "Hi John!",
397 | })
398 | // => {"success":true, "message":"Hi John!"}
399 | })
400 |
401 | app.Listen(3000)
402 | }
403 | ```
404 |
405 | ### WebSocket Upgrade
406 |
407 | 📖 https://fiber.wiki/middleware#websocket
408 |
409 | ```go
410 | import (
411 | "github.com/gofiber/fiber"
412 | "github.com/gofiber/websocket"
413 | )
414 |
415 | func main() {
416 | app := fiber.New()
417 |
418 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
419 | for {
420 | mt, msg, err := c.ReadMessage()
421 | if err != nil {
422 | log.Println("read:", err)
423 | break
424 | }
425 | log.Printf("recv: %s", msg)
426 | err = c.WriteMessage(mt, msg)
427 | if err != nil {
428 | log.Println("write:", err)
429 | break
430 | }
431 | }
432 | }))
433 |
434 | app.Listen(3000)
435 | // ws://localhost:3000/ws
436 | }
437 | ```
438 |
439 | ### Recover middleware
440 |
441 | 📖 https://fiber.wiki/middleware#recover
442 |
443 | ```go
444 | import (
445 | "github.com/gofiber/fiber"
446 | "github.com/gofiber/recover"
447 | )
448 |
449 | func main() {
450 | app := fiber.New()
451 |
452 | // Optional recover config
453 | config := recover.Config{
454 | Handler: func(c *fiber.Ctx, err error) {
455 | c.SendString(err.Error())
456 | c.SendStatus(500)
457 | },
458 | }
459 |
460 | // Logger with custom config
461 | app.Use(recover.New(config))
462 |
463 | app.Listen(3000)
464 | }
465 | ```
466 |
467 |
468 |
469 | ## 💬 媒体
470 |
471 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
472 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
473 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
474 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
475 |
476 | ## 👍 贡献
477 |
478 | 如果您要说声**谢谢**或支持`Fiber`的积极发展:
479 |
480 | 1. 将[GitHub Star](https://github.com/gofiber/fiber/stargazers)添加到项目中。
481 | 2. [在Twitter上](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber)发布有关项目[的推文](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber)。
482 | 3. 在[Medium](https://medium.com/),[Dev.to](https://dev.to/)或个人博客上写评论或教程。
483 | 4. 帮助我们将此`README文件`翻译成其它语言。
484 |
485 | ## ☕ Coffee Supporters
486 |
487 |
533 |
534 |
535 |
536 |
537 |
538 | ## 💻 Code Contributors
539 |
540 |
541 |
542 | ## ⚠️ License
543 |
544 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
545 |
--------------------------------------------------------------------------------
/.github/README_ko.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber는 Express에서 영감을 받고, Go를 위한 가장 빠른 HTTP 엔진인 Fasthttp를 토대로 만들어진 웹 프레임워크 입니다. 비 메모리 할당과 성능을 고려한 빠른 개발을 위해 손쉽게 사용되도록 설계되었습니다.
73 |
74 |
75 | ## ⚡️ 빠른 시작
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Hello, World!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ 설치
94 |
95 | 우선, Go를 [다운로드](https://golang.org/dl/)하고 설치합니다. `1.11` 버전 이상이 요구됩니다.
96 |
97 | [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) 명령어를 이용해 설치가 완료됩니다:
98 |
99 | ```bash
100 | go get -u github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 벤치마크
104 |
105 | 이 테스트들은 [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks)와 [Go Web](https://github.com/smallnest/go-web-framework-benchmark)을 통해 측정되었습니다. 만약 모든 결과를 보고 싶다면, [Wiki](https://fiber.wiki/benchmarks)를 확인해 주세요.
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 특징
113 |
114 | - 견고한 [라우팅](https://fiber.wiki/routing)
115 | - [정적 파일](https://fiber.wiki/application#static) 제공
116 | - 뛰어난 [성능](https://fiber.wiki/benchmarks)
117 | - [적은 메모리](https://fiber.wiki/benchmarks) 공간
118 | - [API 엔드포인트](https://fiber.wiki/context)
119 | - 미들웨어 & [Next](https://fiber.wiki/context#next) 지원
120 | - [빠른](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) 서버 사이드 프로그래밍
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - 더 알고 싶다면, [Fiber 둘러보기](https://fiber.wiki/)
126 |
127 | ## 💡 철학
128 |
129 | [Node.js](https://nodejs.org/en/about/)에서 [Go](https://golang.org/doc/)로 전환하는 새로운 고퍼분들은 웹 어플리케이션이나 마이크로 서비스 개발을 시작할 수 있게 되기 전에 학습 곡선에 시달리고 있습니다. Fiber는 **웹 프레임워크**로서, 새로운 고퍼분들이 따뜻하고 믿음직한 환영을 가지고 빠르게 Go의 세상에 진입할 수 있게 **미니멀리즘**의 개념과 **UNIX 방식**에 따라 개발되었습니다.
130 |
131 | Fiber는 인터넷에서 가장 인기있는 웹 프레임워크인 Express에서 **영감을 받았습니다.** 우리는 Express의 **쉬운** 사용과 Go의 **성능**을 결합하였습니다. 만약 당신이 Node.js (Express 또는 비슷한 것을 사용하여) 로 웹 어플리케이션을 개발한 경험이 있다면, 많은 메소드들과 원리들이 **매우 비슷하게** 느껴질 것 입니다.
132 |
133 | 우리는 **어떤한** 작업, **마감일정**, 개발자의 **기술**이던간에 **빠르고**, **유연하고**, **익숙한** Go 웹 프레임워크를 만들기 위해 사용자들의 [이슈들](https://github.com/gofiber/fiber/issues)을(그리고 모든 인터넷을 통해) **듣고 있습니다**! Express가 자바스크립트 세계에서 하는 것 처럼요.
134 |
135 | ## 👀 예제
136 |
137 | 다음은 일반적인 예제들 입니다.
138 |
139 | > 더 많은 코드 예제를 보고 싶다면, [Recipes 저장소](https://github.com/gofiber/recipes) 또는 [API 문서](https://fiber.wiki)를 방문하세요.
140 |
141 | ### Routing
142 |
143 | 📖 https://fiber.wiki/#basic-routing
144 |
145 |
146 | ```go
147 | func main() {
148 | app := fiber.New()
149 |
150 | // GET /john
151 | app.Get("/:name", func(c *fiber.Ctx) {
152 | fmt.Printf("Hello %s!", c.Params("name"))
153 | // => Hello john!
154 | })
155 |
156 | // GET /john
157 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
158 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
159 | // => Name: john, Age:
160 | })
161 |
162 | // GET /api/register
163 | app.Get("/api*", func(c *fiber.Ctx) {
164 | fmt.Printf("/api%s", c.Params("*"))
165 | // => /api/register
166 | })
167 |
168 | app.Listen(3000)
169 | }
170 | ```
171 |
172 | ### Serve static files
173 |
174 | 📖 https://fiber.wiki/application#static
175 |
176 | ```go
177 | func main() {
178 | app := fiber.New()
179 |
180 | app.Static("/", "/public")
181 | // => http://localhost:3000/js/script.js
182 | // => http://localhost:3000/css/style.css
183 |
184 | app.Static("/prefix", "/public")
185 | // => http://localhost:3000/prefix/js/script.js
186 | // => http://localhost:3000/prefix/css/style.css
187 |
188 | app.Static("*", "/public/index.html")
189 | // => http://localhost:3000/any/path/shows/index/html
190 |
191 | app.Listen(3000)
192 | }
193 | ```
194 |
195 | ### Middleware & Next
196 |
197 | 📖 https://fiber.wiki/routing#middleware
198 | 📖 https://fiber.wiki/context#next
199 |
200 | ```go
201 | func main() {
202 | app := fiber.New()
203 |
204 | // Match any route
205 | app.Use(func(c *fiber.Ctx) {
206 | fmt.Println("First middleware")
207 | c.Next()
208 | })
209 |
210 | // Match all routes starting with /api
211 | app.Use("/api", func(c *fiber.Ctx) {
212 | fmt.Println("Second middleware")
213 | c.Next()
214 | })
215 |
216 | // GET /api/register
217 | app.Get("/api/list", func(c *fiber.Ctx) {
218 | fmt.Println("Last middleware")
219 | c.Send("Hello, World!")
220 | })
221 |
222 | app.Listen(3000)
223 | }
224 | ```
225 |
226 |
227 | 📚 Show more code examples
228 |
229 | ### Template engines
230 |
231 | 📖 https://fiber.wiki/application#settings
232 | 📖 https://fiber.wiki/context#render
233 | 📖 https://fiber.wiki/middleware#template
234 |
235 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
236 |
237 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
238 |
239 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
240 |
241 | ```go
242 | package main
243 |
244 | import (
245 | "github.com/gofiber/fiber"
246 | "github.com/gofiber/template"
247 | )
248 |
249 | func main() {
250 | // You can setup template engine before initiation app:
251 | app := fiber.New(&fiber.Settings{
252 | TemplateEngine: template.Mustache(),
253 | TemplateFolder: "./views",
254 | TemplateExtension: ".tmpl",
255 | })
256 |
257 | // OR after initiation app at any convenient location:
258 | app.Settings.TemplateEngine = template.Mustache()
259 | app.Settings.TemplateFolder = "./views"
260 | app.Settings.TemplateExtension = ".tmpl"
261 |
262 | // And now, you can call template `./views/home.tmpl` like this:
263 | app.Get("/", func(c *fiber.Ctx) {
264 | c.Render("home", fiber.Map{
265 | "title": "Homepage",
266 | "year": 1999,
267 | })
268 | })
269 |
270 | // ...
271 | }
272 | ```
273 |
274 | ### Grouping routes into chains
275 |
276 | 📖 https://fiber.wiki/application#group
277 |
278 | ```go
279 | func main() {
280 | app := fiber.New()
281 |
282 | // Root API route
283 | api := app.Group("/api", cors()) // /api
284 |
285 | // API v1 routes
286 | v1 := api.Group("/v1", mysql()) // /api/v1
287 | v1.Get("/list", handler) // /api/v1/list
288 | v1.Get("/user", handler) // /api/v1/user
289 |
290 | // API v2 routes
291 | v2 := api.Group("/v2", mongodb()) // /api/v2
292 | v2.Get("/list", handler) // /api/v2/list
293 | v2.Get("/user", handler) // /api/v2/user
294 |
295 | // ...
296 | }
297 | ```
298 |
299 | ### Middleware logger
300 |
301 | 📖 https://fiber.wiki/middleware#logger
302 |
303 | ```go
304 | import (
305 | "github.com/gofiber/fiber"
306 | "github.com/gofiber/logger"
307 | )
308 |
309 | func main() {
310 | app := fiber.New()
311 |
312 | // Optional logger config
313 | config := logger.Config{
314 | Format: "${time} - ${method} ${path}\n",
315 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
316 | }
317 |
318 | // Logger with config
319 | app.Use(logger.New(config))
320 |
321 | app.Listen(3000)
322 | }
323 | ```
324 |
325 | ### Cross-Origin Resource Sharing (CORS)
326 |
327 | 📖 https://fiber.wiki/middleware#cors
328 |
329 | ```go
330 | import (
331 | "github.com/gofiber/fiber"
332 | "github.com/gofiber/cors"
333 | )
334 |
335 | func main() {
336 | app := fiber.New()
337 |
338 | // CORS with default config
339 | app.Use(cors.New())
340 |
341 | app.Listen(3000)
342 | }
343 | ```
344 |
345 | Check CORS by passing any domain in `Origin` header:
346 |
347 | ```bash
348 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
349 | ```
350 |
351 | ### Custom 404 response
352 |
353 | 📖 https://fiber.wiki/application#http-methods
354 |
355 | ```go
356 | func main() {
357 | app := fiber.New()
358 |
359 | app.Static("/public")
360 |
361 | app.Get("/demo", func(c *fiber.Ctx) {
362 | c.Send("This is a demo!")
363 | })
364 |
365 | app.Post("/register", func(c *fiber.Ctx) {
366 | c.Send("Welcome!")
367 | })
368 |
369 | // Last middleware to match anything
370 | app.Use(func(c *fiber.Ctx) {
371 | c.SendStatus(404)
372 | // => 404 "Not Found"
373 | })
374 |
375 | app.Listen(3000)
376 | }
377 | ```
378 |
379 | ### JSON Response
380 |
381 | 📖 https://fiber.wiki/context#json
382 |
383 | ```go
384 | type User struct {
385 | Name string `json:"name"`
386 | Age int `json:"age"`
387 | }
388 |
389 | func main() {
390 | app := fiber.New()
391 |
392 | app.Get("/user", func(c *fiber.Ctx) {
393 | c.JSON(&User{"John", 20})
394 | // => {"name":"John", "age":20}
395 | })
396 |
397 | app.Get("/json", func(c *fiber.Ctx) {
398 | c.JSON(fiber.Map{
399 | "success": true,
400 | "message": "Hi John!",
401 | })
402 | // => {"success":true, "message":"Hi John!"}
403 | })
404 |
405 | app.Listen(3000)
406 | }
407 | ```
408 |
409 | ### WebSocket Upgrade
410 |
411 | 📖 https://fiber.wiki/middleware#websocket
412 |
413 | ```go
414 | import (
415 | "github.com/gofiber/fiber"
416 | "github.com/gofiber/websocket"
417 | )
418 |
419 | func main() {
420 | app := fiber.New()
421 |
422 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
423 | for {
424 | mt, msg, err := c.ReadMessage()
425 | if err != nil {
426 | log.Println("read:", err)
427 | break
428 | }
429 | log.Printf("recv: %s", msg)
430 | err = c.WriteMessage(mt, msg)
431 | if err != nil {
432 | log.Println("write:", err)
433 | break
434 | }
435 | }
436 | }))
437 |
438 | app.Listen(3000)
439 | // ws://localhost:3000/ws
440 | }
441 | ```
442 |
443 | ### Recover middleware
444 |
445 | 📖 https://fiber.wiki/middleware#recover
446 |
447 | ```go
448 | import (
449 | "github.com/gofiber/fiber"
450 | "github.com/gofiber/recover"
451 | )
452 |
453 | func main() {
454 | app := fiber.New()
455 |
456 | // Optional recover config
457 | config := recover.Config{
458 | Handler: func(c *fiber.Ctx, err error) {
459 | c.SendString(err.Error())
460 | c.SendStatus(500)
461 | },
462 | }
463 |
464 | // Logger with custom config
465 | app.Use(recover.New(config))
466 |
467 | app.Listen(3000)
468 | }
469 | ```
470 |
471 |
472 | ## 💬 미디어
473 |
474 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
475 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
476 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
477 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
478 |
479 | ## 👍 기여
480 |
481 | `Fiber`의 활발한 개발을 지원하고 감사 인사를 하고 싶다면:
482 |
483 | 1. 프로젝트에 [GitHub Star](https://github.com/gofiber/fiber/stargazers)를 추가하세요.
484 | 2. [트위터에서](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber) 프로젝트에 대해 트윗하세요.
485 | 3. [Medium](https://medium.com/), [Dev.to](https://dev.to/) 또는 개인 블로그에 리뷰 또는 튜토리얼을 작성하세요.
486 | 4. 이 `README`를 다른 언어로 번역하는 것을 도와주세요.
487 |
488 | ## ☕ Coffee Supporters
489 |
490 |
536 |
537 |
538 |
539 |
540 |
541 | ## 💻 Code Contributors
542 |
543 |
544 |
545 | ## ⚠️ License
546 |
547 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
548 |
--------------------------------------------------------------------------------
/.github/README_ja.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | FIberは、Expressに触発されたWebフレームワークです。Go 最速のHTTPエンジンであるFasthttpで作られています。ゼロメモリアロケーションとパフォーマンスを念頭に置いて設計されており、迅速な開発をサポートします。
73 |
74 |
75 |
76 | ## ⚡️ クイックスタート
77 |
78 | ```go
79 | package main
80 |
81 | import "github.com/gofiber/fiber"
82 |
83 | func main() {
84 | app := fiber.New()
85 |
86 | app.Get("/", func(c *fiber.Ctx) {
87 | c.Send("Hello, World!")
88 | })
89 |
90 | app.Listen(3000)
91 | }
92 | ```
93 |
94 | ## ⚙️ インストール
95 |
96 | まず、Goを[ダウンロード](https://golang.org/dl/)してください。 `1.11`以降が必要です。
97 |
98 | そして、[`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them)コマンドを使用してインストールしてください。
99 |
100 | ```bash
101 | go get -u github.com/gofiber/fiber/...
102 | ```
103 |
104 | ## 🤖 ベンチマーク
105 |
106 | これらのテストは[TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks)および[Go Web](https://github.com/smallnest/go-web-framework-benchmark)によって計測を行っています 。すべての結果を表示するには、 [Wiki](https://fiber.wiki/benchmarks)にアクセスしてください。
107 |
108 |
109 |
110 |
111 |
112 |
113 | ## 🎯 機能
114 |
115 | - 堅牢な[ルーティング](https://fiber.wiki/routing)
116 | - [静的ファイル](https://fiber.wiki/application#static)のサポート
117 | - 究極の[パフォーマンス](https://fiber.wiki/benchmarks)
118 | - [低メモリ](https://fiber.wiki/benchmarks)フットプリント
119 | - Express [APIエンドポイント](https://fiber.wiki/context)
120 | - Middlewareと[Next](https://fiber.wiki/context#next)のサポート
121 | - [迅速](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497)なサーバーサイドプログラミング
122 | - [Template engines](https://fiber.wiki/middleware#template)
123 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
124 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
125 | - Available in [10 languages](https://fiber.wiki/)
126 | - [Fiber](https://fiber.wiki/)をもっと知る
127 |
128 | ## 💡 哲学
129 |
130 | [Node.js](https://nodejs.org/en/about/)から[Go](https://golang.org/doc/) に乗り換えようとしている新しいGopherはWebフレームワークやマイクロサービスの構築を始める前に多くを学ばなければなりません。
131 | しかし、 **Webフレームワーク**であるFiberは**ミニマリズム**と**UNIX哲学**をもとに作られているため、新しいGopherはスムーズにGoの世界に入ることができます。
132 |
133 | Fiberは人気の高いWebフレームワークであるExpressjsに**インスパイア**されています。
134 | わたしたちは Expressの**手軽さ**とGoの**パフォーマンス**を組み合わせました。
135 | もしも、WebフレームワークをExpress等のNode.jsフレームワークで実装した経験があれば、多くの方法や原理がとても**馴染み深い**でしょう。
136 |
137 | ## 👀 例
138 |
139 | 以下に一般的な例をいくつか示します。他のコード例をご覧になりたい場合は、 [Recipesリポジトリ](https://github.com/gofiber/recipes)または[APIドキュメント](https://fiber.wiki)にアクセスしてください。
140 |
141 | ### Routing
142 |
143 | 📖 https://fiber.wiki/#basic-routing
144 |
145 |
146 | ```go
147 | func main() {
148 | app := fiber.New()
149 |
150 | // GET /john
151 | app.Get("/:name", func(c *fiber.Ctx) {
152 | fmt.Printf("Hello %s!", c.Params("name"))
153 | // => Hello john!
154 | })
155 |
156 | // GET /john
157 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
158 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
159 | // => Name: john, Age:
160 | })
161 |
162 | // GET /api/register
163 | app.Get("/api*", func(c *fiber.Ctx) {
164 | fmt.Printf("/api%s", c.Params("*"))
165 | // => /api/register
166 | })
167 |
168 | app.Listen(3000)
169 | }
170 | ```
171 |
172 | ### Serve static files
173 |
174 | 📖 https://fiber.wiki/application#static
175 |
176 | ```go
177 | func main() {
178 | app := fiber.New()
179 |
180 | app.Static("/", "/public")
181 | // => http://localhost:3000/js/script.js
182 | // => http://localhost:3000/css/style.css
183 |
184 | app.Static("/prefix", "/public")
185 | // => http://localhost:3000/prefix/js/script.js
186 | // => http://localhost:3000/prefix/css/style.css
187 |
188 | app.Static("*", "/public/index.html")
189 | // => http://localhost:3000/any/path/shows/index/html
190 |
191 | app.Listen(3000)
192 | }
193 | ```
194 |
195 | ### Middleware & Next
196 |
197 | 📖 https://fiber.wiki/routing#middleware
198 | 📖 https://fiber.wiki/context#next
199 |
200 | ```go
201 | func main() {
202 | app := fiber.New()
203 |
204 | // Match any route
205 | app.Use(func(c *fiber.Ctx) {
206 | fmt.Println("First middleware")
207 | c.Next()
208 | })
209 |
210 | // Match all routes starting with /api
211 | app.Use("/api", func(c *fiber.Ctx) {
212 | fmt.Println("Second middleware")
213 | c.Next()
214 | })
215 |
216 | // GET /api/register
217 | app.Get("/api/list", func(c *fiber.Ctx) {
218 | fmt.Println("Last middleware")
219 | c.Send("Hello, World!")
220 | })
221 |
222 | app.Listen(3000)
223 | }
224 | ```
225 |
226 |
227 | 📚 Show more code examples
228 |
229 | ### Template engines
230 |
231 | 📖 https://fiber.wiki/application#settings
232 | 📖 https://fiber.wiki/context#render
233 | 📖 https://fiber.wiki/middleware#template
234 |
235 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
236 |
237 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
238 |
239 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
240 |
241 | ```go
242 | package main
243 |
244 | import (
245 | "github.com/gofiber/fiber"
246 | "github.com/gofiber/template"
247 | )
248 |
249 | func main() {
250 | // You can setup template engine before initiation app:
251 | app := fiber.New(&fiber.Settings{
252 | TemplateEngine: template.Mustache(),
253 | TemplateFolder: "./views",
254 | TemplateExtension: ".tmpl",
255 | })
256 |
257 | // OR after initiation app at any convenient location:
258 | app.Settings.TemplateEngine = template.Mustache()
259 | app.Settings.TemplateFolder = "./views"
260 | app.Settings.TemplateExtension = ".tmpl"
261 |
262 | // And now, you can call template `./views/home.tmpl` like this:
263 | app.Get("/", func(c *fiber.Ctx) {
264 | c.Render("home", fiber.Map{
265 | "title": "Homepage",
266 | "year": 1999,
267 | })
268 | })
269 |
270 | // ...
271 | }
272 | ```
273 |
274 | ### Grouping routes into chains
275 |
276 | 📖 https://fiber.wiki/application#group
277 |
278 | ```go
279 | func main() {
280 | app := fiber.New()
281 |
282 | // Root API route
283 | api := app.Group("/api", cors()) // /api
284 |
285 | // API v1 routes
286 | v1 := api.Group("/v1", mysql()) // /api/v1
287 | v1.Get("/list", handler) // /api/v1/list
288 | v1.Get("/user", handler) // /api/v1/user
289 |
290 | // API v2 routes
291 | v2 := api.Group("/v2", mongodb()) // /api/v2
292 | v2.Get("/list", handler) // /api/v2/list
293 | v2.Get("/user", handler) // /api/v2/user
294 |
295 | // ...
296 | }
297 | ```
298 |
299 | ### Middleware logger
300 |
301 | 📖 https://fiber.wiki/middleware#logger
302 |
303 | ```go
304 | import (
305 | "github.com/gofiber/fiber"
306 | "github.com/gofiber/logger"
307 | )
308 |
309 | func main() {
310 | app := fiber.New()
311 |
312 | // Optional logger config
313 | config := logger.Config{
314 | Format: "${time} - ${method} ${path}\n",
315 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
316 | }
317 |
318 | // Logger with config
319 | app.Use(logger.New(config))
320 |
321 | app.Listen(3000)
322 | }
323 | ```
324 |
325 | ### Cross-Origin Resource Sharing (CORS)
326 |
327 | 📖 https://fiber.wiki/middleware#cors
328 |
329 | ```go
330 | import (
331 | "github.com/gofiber/fiber"
332 | "github.com/gofiber/cors"
333 | )
334 |
335 | func main() {
336 | app := fiber.New()
337 |
338 | // CORS with default config
339 | app.Use(cors.New())
340 |
341 | app.Listen(3000)
342 | }
343 | ```
344 |
345 | Check CORS by passing any domain in `Origin` header:
346 |
347 | ```bash
348 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
349 | ```
350 |
351 | ### Custom 404 response
352 |
353 | 📖 https://fiber.wiki/application#http-methods
354 |
355 | ```go
356 | func main() {
357 | app := fiber.New()
358 |
359 | app.Static("/public")
360 |
361 | app.Get("/demo", func(c *fiber.Ctx) {
362 | c.Send("This is a demo!")
363 | })
364 |
365 | app.Post("/register", func(c *fiber.Ctx) {
366 | c.Send("Welcome!")
367 | })
368 |
369 | // Last middleware to match anything
370 | app.Use(func(c *fiber.Ctx) {
371 | c.SendStatus(404)
372 | // => 404 "Not Found"
373 | })
374 |
375 | app.Listen(3000)
376 | }
377 | ```
378 |
379 | ### JSON Response
380 |
381 | 📖 https://fiber.wiki/context#json
382 |
383 | ```go
384 | type User struct {
385 | Name string `json:"name"`
386 | Age int `json:"age"`
387 | }
388 |
389 | func main() {
390 | app := fiber.New()
391 |
392 | app.Get("/user", func(c *fiber.Ctx) {
393 | c.JSON(&User{"John", 20})
394 | // => {"name":"John", "age":20}
395 | })
396 |
397 | app.Get("/json", func(c *fiber.Ctx) {
398 | c.JSON(fiber.Map{
399 | "success": true,
400 | "message": "Hi John!",
401 | })
402 | // => {"success":true, "message":"Hi John!"}
403 | })
404 |
405 | app.Listen(3000)
406 | }
407 | ```
408 |
409 | ### WebSocket Upgrade
410 |
411 | 📖 https://fiber.wiki/middleware#websocket
412 |
413 | ```go
414 | import (
415 | "github.com/gofiber/fiber"
416 | "github.com/gofiber/websocket"
417 | )
418 |
419 | func main() {
420 | app := fiber.New()
421 |
422 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
423 | for {
424 | mt, msg, err := c.ReadMessage()
425 | if err != nil {
426 | log.Println("read:", err)
427 | break
428 | }
429 | log.Printf("recv: %s", msg)
430 | err = c.WriteMessage(mt, msg)
431 | if err != nil {
432 | log.Println("write:", err)
433 | break
434 | }
435 | }
436 | }))
437 |
438 | app.Listen(3000)
439 | // ws://localhost:3000/ws
440 | }
441 | ```
442 |
443 | ### Recover middleware
444 |
445 | 📖 https://fiber.wiki/middleware#recover
446 |
447 | ```go
448 | import (
449 | "github.com/gofiber/fiber"
450 | "github.com/gofiber/recover"
451 | )
452 |
453 | func main() {
454 | app := fiber.New()
455 |
456 | // Optional recover config
457 | config := recover.Config{
458 | Handler: func(c *fiber.Ctx, err error) {
459 | c.SendString(err.Error())
460 | c.SendStatus(500)
461 | },
462 | }
463 |
464 | // Logger with custom config
465 | app.Use(recover.New(config))
466 |
467 | app.Listen(3000)
468 | }
469 | ```
470 |
471 |
472 | ## 💬 メディア
473 |
474 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
475 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
476 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
477 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
478 |
479 | ## 👍 貢献する
480 |
481 | `Fiber`に開発支援してくださるなら:
482 |
483 | 1. [GitHub Star](https://github.com/gofiber/fiber/stargazers)をつけてください 。
484 | 2. [あなたのTwitterで](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber)プロジェクトについてツイートしてください。
485 | 3. [Medium](https://medium.com/) 、 [Dev.to、](https://dev.to/)または個人のブログでレビューまたはチュートリアルを書いてください。
486 | 4. この`README`と[APIドキュメント](https://fiber.wiki/)を別の言語に翻訳するためにご協力ください。
487 |
488 |
489 |
490 | ## ☕ Coffee Supporters
491 |
492 |
538 |
539 |
540 |
541 |
542 |
543 | ## 💻 Code Contributors
544 |
545 |
546 |
547 | ## ⚠️ License
548 |
549 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
550 |
--------------------------------------------------------------------------------
/.github/README_tr.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber, Go için en hızlı HTTP motoru olan Fasthttp üzerine inşa edilmiş, Express den ilham alan bir web çatısıdır. Sıfır bellek ayırma ve performans göz önünde bulundurularak hızlı geliştirme için işleri kolaylaştırmak üzere tasarlandı.
73 |
74 |
75 | ## ⚡️ Hızlı Başlangıç
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Merhaba dünya!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ Kurulum
94 |
95 | İlk önce, Go yu [indirip](https://golang.org/dl/) kuruyoruz. `1.11` veya daha yeni sürüm gereklidir.
96 |
97 | [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) komutunu kullanarak kurulumu tamamlıyoruz:
98 |
99 | ```bash
100 | go get -u github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 Performans Ölçümleri
104 |
105 | Bu testler [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) ve [Go Web](https://github.com/smallnest/go-web-framework-benchmark) ile koşuldu. Bütün sonuçları görmek için lütfen [Wiki](https://fiber.wiki/benchmarks) sayfasını ziyaret ediniz.
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 Özellikler
113 |
114 | - Güçlü [rotalar](https://fiber.wiki/routing)
115 | - [Statik dosya](https://fiber.wiki/application#static) yönetimi
116 | - Olağanüstü [performans](https://fiber.wiki/benchmarks)
117 | - [Düşük bellek](https://fiber.wiki/benchmarks) tüketimi
118 | - [API uç noktaları](https://fiber.wiki/context)
119 | - Ara katman & [Sonraki](https://fiber.wiki/context#next) desteği
120 | - [Hızlı](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) sunucu taraflı programlama
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - Ve daha fazlası, [Fiber ı keşfet](https://fiber.wiki/)
126 |
127 | ## 💡 Felsefe
128 |
129 | [Node.js](https://nodejs.org/en/about/) den [Go](https://golang.org/doc/) ya geçen yeni gopher lar kendi web uygulamalarını ve mikroservislerini yazmaya başlamadan önce dili öğrenmek ile uğraşıyorlar. Fiber, bir **web çatısı** olarak, **minimalizm** ve **UNIX yolu**nu izlemek fikri ile oluşturuldu. Böylece yeni gopher lar sıcak ve güvenilir bir hoşgeldin ile Go dünyasına giriş yapabilirler.
130 |
131 | Fiber internet üzerinde en popüler olan Express web çatısından **esinlenmiştir**. Biz Express in **kolaylığını** ve Go nun **ham performansını** birleştirdik. Daha önce Node.js üzerinde (Express veya benzerini kullanarak) bir web uygulaması geliştirdiyseniz, pek çok metod ve prensip size **çok tanıdık** gelecektir.
132 |
133 | ## 👀 Örnekler
134 |
135 | Aşağıda yaygın örneklerden bazıları listelenmiştir. Daha fazla kod örneği görmek için, lütfen [Kod depomuzu](https://github.com/gofiber/recipes) veya [API dökümantasyonunu](https://fiber.wiki) ziyaret ediniz.
136 |
137 | ### Routing
138 |
139 | 📖 https://fiber.wiki/#basic-routing
140 |
141 |
142 | ```go
143 | func main() {
144 | app := fiber.New()
145 |
146 | // GET /john
147 | app.Get("/:name", func(c *fiber.Ctx) {
148 | fmt.Printf("Hello %s!", c.Params("name"))
149 | // => Hello john!
150 | })
151 |
152 | // GET /john
153 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
154 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
155 | // => Name: john, Age:
156 | })
157 |
158 | // GET /api/register
159 | app.Get("/api*", func(c *fiber.Ctx) {
160 | fmt.Printf("/api%s", c.Params("*"))
161 | // => /api/register
162 | })
163 |
164 | app.Listen(3000)
165 | }
166 | ```
167 |
168 | ### Serve static files
169 |
170 | 📖 https://fiber.wiki/application#static
171 |
172 | ```go
173 | func main() {
174 | app := fiber.New()
175 |
176 | app.Static("/", "/public")
177 | // => http://localhost:3000/js/script.js
178 | // => http://localhost:3000/css/style.css
179 |
180 | app.Static("/prefix", "/public")
181 | // => http://localhost:3000/prefix/js/script.js
182 | // => http://localhost:3000/prefix/css/style.css
183 |
184 | app.Static("*", "/public/index.html")
185 | // => http://localhost:3000/any/path/shows/index/html
186 |
187 | app.Listen(3000)
188 | }
189 | ```
190 |
191 | ### Middleware & Next
192 |
193 | 📖 https://fiber.wiki/routing#middleware
194 | 📖 https://fiber.wiki/context#next
195 |
196 | ```go
197 | func main() {
198 | app := fiber.New()
199 |
200 | // Match any route
201 | app.Use(func(c *fiber.Ctx) {
202 | fmt.Println("First middleware")
203 | c.Next()
204 | })
205 |
206 | // Match all routes starting with /api
207 | app.Use("/api", func(c *fiber.Ctx) {
208 | fmt.Println("Second middleware")
209 | c.Next()
210 | })
211 |
212 | // GET /api/register
213 | app.Get("/api/list", func(c *fiber.Ctx) {
214 | fmt.Println("Last middleware")
215 | c.Send("Hello, World!")
216 | })
217 |
218 | app.Listen(3000)
219 | }
220 | ```
221 |
222 |
223 | 📚 Show more code examples
224 |
225 | ### Template engines
226 |
227 | 📖 https://fiber.wiki/application#settings
228 | 📖 https://fiber.wiki/context#render
229 | 📖 https://fiber.wiki/middleware#template
230 |
231 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
232 |
233 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
234 |
235 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
236 |
237 | ```go
238 | package main
239 |
240 | import (
241 | "github.com/gofiber/fiber"
242 | "github.com/gofiber/template"
243 | )
244 |
245 | func main() {
246 | // You can setup template engine before initiation app:
247 | app := fiber.New(&fiber.Settings{
248 | TemplateEngine: template.Mustache(),
249 | TemplateFolder: "./views",
250 | TemplateExtension: ".tmpl",
251 | })
252 |
253 | // OR after initiation app at any convenient location:
254 | app.Settings.TemplateEngine = template.Mustache()
255 | app.Settings.TemplateFolder = "./views"
256 | app.Settings.TemplateExtension = ".tmpl"
257 |
258 | // And now, you can call template `./views/home.tmpl` like this:
259 | app.Get("/", func(c *fiber.Ctx) {
260 | c.Render("home", fiber.Map{
261 | "title": "Homepage",
262 | "year": 1999,
263 | })
264 | })
265 |
266 | // ...
267 | }
268 | ```
269 |
270 | ### Grouping routes into chains
271 |
272 | 📖 https://fiber.wiki/application#group
273 |
274 | ```go
275 | func main() {
276 | app := fiber.New()
277 |
278 | // Root API route
279 | api := app.Group("/api", cors()) // /api
280 |
281 | // API v1 routes
282 | v1 := api.Group("/v1", mysql()) // /api/v1
283 | v1.Get("/list", handler) // /api/v1/list
284 | v1.Get("/user", handler) // /api/v1/user
285 |
286 | // API v2 routes
287 | v2 := api.Group("/v2", mongodb()) // /api/v2
288 | v2.Get("/list", handler) // /api/v2/list
289 | v2.Get("/user", handler) // /api/v2/user
290 |
291 | // ...
292 | }
293 | ```
294 |
295 | ### Middleware logger
296 |
297 | 📖 https://fiber.wiki/middleware#logger
298 |
299 | ```go
300 | import (
301 | "github.com/gofiber/fiber"
302 | "github.com/gofiber/logger"
303 | )
304 |
305 | func main() {
306 | app := fiber.New()
307 |
308 | // Optional logger config
309 | config := logger.Config{
310 | Format: "${time} - ${method} ${path}\n",
311 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
312 | }
313 |
314 | // Logger with config
315 | app.Use(logger.New(config))
316 |
317 | app.Listen(3000)
318 | }
319 | ```
320 |
321 | ### Cross-Origin Resource Sharing (CORS)
322 |
323 | 📖 https://fiber.wiki/middleware#cors
324 |
325 | ```go
326 | import (
327 | "github.com/gofiber/fiber"
328 | "github.com/gofiber/cors"
329 | )
330 |
331 | func main() {
332 | app := fiber.New()
333 |
334 | // CORS with default config
335 | app.Use(cors.New())
336 |
337 | app.Listen(3000)
338 | }
339 | ```
340 |
341 | Check CORS by passing any domain in `Origin` header:
342 |
343 | ```bash
344 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
345 | ```
346 |
347 | ### Custom 404 response
348 |
349 | 📖 https://fiber.wiki/application#http-methods
350 |
351 | ```go
352 | func main() {
353 | app := fiber.New()
354 |
355 | app.Static("/public")
356 |
357 | app.Get("/demo", func(c *fiber.Ctx) {
358 | c.Send("This is a demo!")
359 | })
360 |
361 | app.Post("/register", func(c *fiber.Ctx) {
362 | c.Send("Welcome!")
363 | })
364 |
365 | // Last middleware to match anything
366 | app.Use(func(c *fiber.Ctx) {
367 | c.SendStatus(404)
368 | // => 404 "Not Found"
369 | })
370 |
371 | app.Listen(3000)
372 | }
373 | ```
374 |
375 | ### JSON Response
376 |
377 | 📖 https://fiber.wiki/context#json
378 |
379 | ```go
380 | type User struct {
381 | Name string `json:"name"`
382 | Age int `json:"age"`
383 | }
384 |
385 | func main() {
386 | app := fiber.New()
387 |
388 | app.Get("/user", func(c *fiber.Ctx) {
389 | c.JSON(&User{"John", 20})
390 | // => {"name":"John", "age":20}
391 | })
392 |
393 | app.Get("/json", func(c *fiber.Ctx) {
394 | c.JSON(fiber.Map{
395 | "success": true,
396 | "message": "Hi John!",
397 | })
398 | // => {"success":true, "message":"Hi John!"}
399 | })
400 |
401 | app.Listen(3000)
402 | }
403 | ```
404 |
405 | ### WebSocket Upgrade
406 |
407 | 📖 https://fiber.wiki/middleware#websocket
408 |
409 | ```go
410 | import (
411 | "github.com/gofiber/fiber"
412 | "github.com/gofiber/websocket"
413 | )
414 |
415 | func main() {
416 | app := fiber.New()
417 |
418 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
419 | for {
420 | mt, msg, err := c.ReadMessage()
421 | if err != nil {
422 | log.Println("read:", err)
423 | break
424 | }
425 | log.Printf("recv: %s", msg)
426 | err = c.WriteMessage(mt, msg)
427 | if err != nil {
428 | log.Println("write:", err)
429 | break
430 | }
431 | }
432 | }))
433 |
434 | app.Listen(3000)
435 | // ws://localhost:3000/ws
436 | }
437 | ```
438 |
439 | ### Recover middleware
440 |
441 | 📖 https://fiber.wiki/middleware#recover
442 |
443 | ```go
444 | import (
445 | "github.com/gofiber/fiber"
446 | "github.com/gofiber/recover"
447 | )
448 |
449 | func main() {
450 | app := fiber.New()
451 |
452 | // Optional recover config
453 | config := recover.Config{
454 | Handler: func(c *fiber.Ctx, err error) {
455 | c.SendString(err.Error())
456 | c.SendStatus(500)
457 | },
458 | }
459 |
460 | // Logger with custom config
461 | app.Use(recover.New(config))
462 |
463 | app.Listen(3000)
464 | }
465 | ```
466 |
467 |
468 | ## 💬 Medya
469 |
470 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
471 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
472 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
473 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
474 |
475 | ## 👍 Destek
476 |
477 | Eğer **teşekkür etmek** ve/veya `Fiber` ın aktif geliştirilmesini desteklemek istiyorsanız:
478 |
479 | 1. Projeye [GitHub Yıldızı](https://github.com/gofiber/fiber/stargazers) verin.
480 | 2. [Twitter hesabınızdan](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber) proje hakkında tweet atın.
481 | 3. [Medium](https://medium.com/), [Dev.to](https://dev.to/) veya kişisel blog üzerinden bir inceleme veya eğitici yazı yazın.
482 | 4. Bu `BENİOKU` sayfasını başka bir dile tercüme etmek için bize yardım edin.
483 |
484 |
485 | ## ☕ Coffee Destekleyenler
486 |
487 |
533 |
534 |
535 |
536 |
537 |
538 | ## 💻 Code Contributors
539 |
540 |
541 |
542 | ## ⚠️ License
543 |
544 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
545 |
--------------------------------------------------------------------------------
/.github/README_pt.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber é um framework web inspirado no Express, construído sobre o Fasthttp, o motor HTTP mais rápido do Go. Projetado para facilitar e acelerar o desenvolvimento, com zero de alocação de memória e desempenho em mente.
73 |
74 |
75 | ## ⚡️ Início rápido
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Hello, World!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ Instalação
94 |
95 | Primeiro de tudo, faça o [download](https://golang.org/dl/) e instale o Go. É necessário a versão `1.11` ou superior.
96 |
97 | A instalação é feita usando o comando [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) :
98 |
99 | ```bash
100 | go get -u github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 Benchmarks
104 |
105 | Esses testes são realizados pelo [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) e [Go Web](https://github.com/smallnest/go-web-framework-benchmark). Se você quiser ver todos os resultados, visite nosso [Wiki](https://fiber.wiki/benchmarks) .
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 Recursos
113 |
114 | - [Roteamento](https://fiber.wiki/routing) robusto
115 | - Servir [arquivos estáticos](https://fiber.wiki/application#static)
116 | - [Desempenho](https://fiber.wiki/benchmarks) extremo
117 | - [Baixo consumo de memória](https://fiber.wiki/benchmarks)
118 | - [API de rotas](https://fiber.wiki/context)
119 | - Suporte para Middleware e [Next](https://fiber.wiki/context#next)
120 | - Programação [rápida](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) de aplicações de servidor
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - E muito mais, [explore o Fiber](https://fiber.wiki/)
126 |
127 | ## 💡 Filosofia
128 |
129 | Os novos gophers que mudaram do [Node.js](https://nodejs.org/en/about/) para o [Go](https://golang.org/doc/) estão tendo que lidar com uma curva de aprendizado antes que possam começar a criar seus aplicativos web ou microsserviços. O Fiber, como um **framework web**, foi criado com a ideia de ser **minimalista** e seguindo o **caminho UNIX**, para que novos gophers possam, rapidamente, entrar no mundo do Go com uma recepção calorosa e confiável.
130 |
131 | O Fiber é **inspirado** no Express, o framework web mais popular da Internet. Combinamos a **facilidade** do Express e o **desempenho bruto** do Go. Se você já implementou um aplicativo web com Node.js ( _usando Express.js ou similar_ ), então muitos métodos e princípios parecerão **muito comuns** para você.
132 |
133 | ## 👀 Exemplos
134 |
135 | Listados abaixo estão alguns exemplos comuns. Se você quiser ver mais exemplos de código, visite nosso [repositório de receitas](https://github.com/gofiber/recipes) ou a [documentação da API](https://fiber.wiki).
136 |
137 | ### Routing
138 |
139 | 📖 https://fiber.wiki/#basic-routing
140 |
141 |
142 | ```go
143 | func main() {
144 | app := fiber.New()
145 |
146 | // GET /john
147 | app.Get("/:name", func(c *fiber.Ctx) {
148 | fmt.Printf("Hello %s!", c.Params("name"))
149 | // => Hello john!
150 | })
151 |
152 | // GET /john
153 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
154 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
155 | // => Name: john, Age:
156 | })
157 |
158 | // GET /api/register
159 | app.Get("/api*", func(c *fiber.Ctx) {
160 | fmt.Printf("/api%s", c.Params("*"))
161 | // => /api/register
162 | })
163 |
164 | app.Listen(3000)
165 | }
166 | ```
167 |
168 | ### Serve static files
169 |
170 | 📖 https://fiber.wiki/application#static
171 |
172 | ```go
173 | func main() {
174 | app := fiber.New()
175 |
176 | app.Static("/", "/public")
177 | // => http://localhost:3000/js/script.js
178 | // => http://localhost:3000/css/style.css
179 |
180 | app.Static("/prefix", "/public")
181 | // => http://localhost:3000/prefix/js/script.js
182 | // => http://localhost:3000/prefix/css/style.css
183 |
184 | app.Static("*", "/public/index.html")
185 | // => http://localhost:3000/any/path/shows/index/html
186 |
187 | app.Listen(3000)
188 | }
189 | ```
190 |
191 | ### Middleware & Next
192 |
193 | 📖 https://fiber.wiki/routing#middleware
194 | 📖 https://fiber.wiki/context#next
195 |
196 | ```go
197 | func main() {
198 | app := fiber.New()
199 |
200 | // Match any route
201 | app.Use(func(c *fiber.Ctx) {
202 | fmt.Println("First middleware")
203 | c.Next()
204 | })
205 |
206 | // Match all routes starting with /api
207 | app.Use("/api", func(c *fiber.Ctx) {
208 | fmt.Println("Second middleware")
209 | c.Next()
210 | })
211 |
212 | // GET /api/register
213 | app.Get("/api/list", func(c *fiber.Ctx) {
214 | fmt.Println("Last middleware")
215 | c.Send("Hello, World!")
216 | })
217 |
218 | app.Listen(3000)
219 | }
220 | ```
221 |
222 |
223 | 📚 Show more code examples
224 |
225 | ### Template engines
226 |
227 | 📖 https://fiber.wiki/application#settings
228 | 📖 https://fiber.wiki/context#render
229 | 📖 https://fiber.wiki/middleware#template
230 |
231 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
232 |
233 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
234 |
235 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
236 |
237 | ```go
238 | package main
239 |
240 | import (
241 | "github.com/gofiber/fiber"
242 | "github.com/gofiber/template"
243 | )
244 |
245 | func main() {
246 | // You can setup template engine before initiation app:
247 | app := fiber.New(&fiber.Settings{
248 | TemplateEngine: template.Mustache(),
249 | TemplateFolder: "./views",
250 | TemplateExtension: ".tmpl",
251 | })
252 |
253 | // OR after initiation app at any convenient location:
254 | app.Settings.TemplateEngine = template.Mustache()
255 | app.Settings.TemplateFolder = "./views"
256 | app.Settings.TemplateExtension = ".tmpl"
257 |
258 | // And now, you can call template `./views/home.tmpl` like this:
259 | app.Get("/", func(c *fiber.Ctx) {
260 | c.Render("home", fiber.Map{
261 | "title": "Homepage",
262 | "year": 1999,
263 | })
264 | })
265 |
266 | // ...
267 | }
268 | ```
269 |
270 | ### Grouping routes into chains
271 |
272 | 📖 https://fiber.wiki/application#group
273 |
274 | ```go
275 | func main() {
276 | app := fiber.New()
277 |
278 | // Root API route
279 | api := app.Group("/api", cors()) // /api
280 |
281 | // API v1 routes
282 | v1 := api.Group("/v1", mysql()) // /api/v1
283 | v1.Get("/list", handler) // /api/v1/list
284 | v1.Get("/user", handler) // /api/v1/user
285 |
286 | // API v2 routes
287 | v2 := api.Group("/v2", mongodb()) // /api/v2
288 | v2.Get("/list", handler) // /api/v2/list
289 | v2.Get("/user", handler) // /api/v2/user
290 |
291 | // ...
292 | }
293 | ```
294 |
295 | ### Middleware logger
296 |
297 | 📖 https://fiber.wiki/middleware#logger
298 |
299 | ```go
300 | import (
301 | "github.com/gofiber/fiber"
302 | "github.com/gofiber/logger"
303 | )
304 |
305 | func main() {
306 | app := fiber.New()
307 |
308 | // Optional logger config
309 | config := logger.Config{
310 | Format: "${time} - ${method} ${path}\n",
311 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
312 | }
313 |
314 | // Logger with config
315 | app.Use(logger.New(config))
316 |
317 | app.Listen(3000)
318 | }
319 | ```
320 |
321 | ### Cross-Origin Resource Sharing (CORS)
322 |
323 | 📖 https://fiber.wiki/middleware#cors
324 |
325 | ```go
326 | import (
327 | "github.com/gofiber/fiber"
328 | "github.com/gofiber/cors"
329 | )
330 |
331 | func main() {
332 | app := fiber.New()
333 |
334 | // CORS with default config
335 | app.Use(cors.New())
336 |
337 | app.Listen(3000)
338 | }
339 | ```
340 |
341 | Check CORS by passing any domain in `Origin` header:
342 |
343 | ```bash
344 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
345 | ```
346 |
347 | ### Custom 404 response
348 |
349 | 📖 https://fiber.wiki/application#http-methods
350 |
351 | ```go
352 | func main() {
353 | app := fiber.New()
354 |
355 | app.Static("/public")
356 |
357 | app.Get("/demo", func(c *fiber.Ctx) {
358 | c.Send("This is a demo!")
359 | })
360 |
361 | app.Post("/register", func(c *fiber.Ctx) {
362 | c.Send("Welcome!")
363 | })
364 |
365 | // Last middleware to match anything
366 | app.Use(func(c *fiber.Ctx) {
367 | c.SendStatus(404)
368 | // => 404 "Not Found"
369 | })
370 |
371 | app.Listen(3000)
372 | }
373 | ```
374 |
375 | ### JSON Response
376 |
377 | 📖 https://fiber.wiki/context#json
378 |
379 | ```go
380 | type User struct {
381 | Name string `json:"name"`
382 | Age int `json:"age"`
383 | }
384 |
385 | func main() {
386 | app := fiber.New()
387 |
388 | app.Get("/user", func(c *fiber.Ctx) {
389 | c.JSON(&User{"John", 20})
390 | // => {"name":"John", "age":20}
391 | })
392 |
393 | app.Get("/json", func(c *fiber.Ctx) {
394 | c.JSON(fiber.Map{
395 | "success": true,
396 | "message": "Hi John!",
397 | })
398 | // => {"success":true, "message":"Hi John!"}
399 | })
400 |
401 | app.Listen(3000)
402 | }
403 | ```
404 |
405 | ### WebSocket Upgrade
406 |
407 | 📖 https://fiber.wiki/middleware#websocket
408 |
409 | ```go
410 | import (
411 | "github.com/gofiber/fiber"
412 | "github.com/gofiber/websocket"
413 | )
414 |
415 | func main() {
416 | app := fiber.New()
417 |
418 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
419 | for {
420 | mt, msg, err := c.ReadMessage()
421 | if err != nil {
422 | log.Println("read:", err)
423 | break
424 | }
425 | log.Printf("recv: %s", msg)
426 | err = c.WriteMessage(mt, msg)
427 | if err != nil {
428 | log.Println("write:", err)
429 | break
430 | }
431 | }
432 | }))
433 |
434 | app.Listen(3000)
435 | // ws://localhost:3000/ws
436 | }
437 | ```
438 |
439 | ### Recover middleware
440 |
441 | 📖 https://fiber.wiki/middleware#recover
442 |
443 | ```go
444 | import (
445 | "github.com/gofiber/fiber"
446 | "github.com/gofiber/recover"
447 | )
448 |
449 | func main() {
450 | app := fiber.New()
451 |
452 | // Optional recover config
453 | config := recover.Config{
454 | Handler: func(c *fiber.Ctx, err error) {
455 | c.SendString(err.Error())
456 | c.SendStatus(500)
457 | },
458 | }
459 |
460 | // Logger with custom config
461 | app.Use(recover.New(config))
462 |
463 | app.Listen(3000)
464 | }
465 | ```
466 |
467 |
468 | ## 💬 Mídia
469 |
470 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
471 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
472 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
473 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
474 |
475 | ## 👍 Contribuindo
476 |
477 | Se você quer **agradecer** e/ou apoiar o desenvolvimento ativo do `Fiber`:
478 |
479 | 1. Deixe uma [estrela no GitHub](https://github.com/gofiber/fiber/stargazers) do projeto.
480 | 2. Tweet sobre o projeto [no seu Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber) .
481 | 3. Escreva um review ou tutorial no [Medium](https://medium.com/), [Dev.to](https://dev.to/) ou blog pessoal.
482 | 4. Nos ajude a traduzir esses `README` e a [documentação da API](https://fiber.wiki/) para outros idiomas.
483 |
484 | ## ☕ Coffee Supporters
485 |
486 |
532 |
533 |
534 |
535 |
536 |
537 | ## 💻 Code Contributors
538 |
539 |
540 |
541 | ## ⚠️ License
542 |
543 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
544 |
--------------------------------------------------------------------------------
/.github/README_fr.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber est un framework web inspiré d' Express. Il se base sur Fasthttp, l'implémentation HTTP de Go la plus rapide. Conçu pour faciliter les choses pour des développements rapides, Fiber garde à l'esprit l'absence d'allocations mémoires, ainsi que les performances.
73 |
74 |
75 | ## ⚡️ Quickstart
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Hello, World!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ Installation
94 |
95 | Premièrement, [téléchargez](https://golang.org/dl/) et installez Go. Version `1.11` ou supérieur requise.
96 |
97 | L'installation est ensuite lancée via la commande [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them):
98 |
99 | ```bash
100 | go get -u github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 Benchmarks
104 |
105 | Ces tests sont effectués par [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) et [Go Web](https://github.com/smallnest/go-web-framework-benchmark). Si vous voulez voir tous les résultats, n'hésitez pas à consulter notre [Wiki](https://fiber.wiki/benchmarks).
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 Features
113 |
114 | - [Routing](https://fiber.wiki/routing) robuste
115 | - Serve [static files](https://fiber.wiki/application#static)
116 | - [Performances](https://fiber.wiki/benchmarks) extrêmes
117 | - [Faible empreinte mémoire](https://fiber.wiki/benchmarks)
118 | - [API endpoints](https://fiber.wiki/context)
119 | - Middleware & [Next](https://fiber.wiki/context#next) support
120 | - Programmation côté serveur [rapide](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497)
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - Et plus encore, [explorez Fiber](https://fiber.wiki/)
126 |
127 | ## 💡 Philosophie
128 |
129 | Les nouveaux gophers qui passent de [Node.js](https://nodejs.org/en/about/) à [Go](https://golang.org/doc/) sont confrontés à une courbe d'apprentissage, avant de pouvoir construire leurs applications web et microservices. Fiber, en tant que **framework web**, a été mis au point avec en tête l'idée de **minimalisme**, tout en suivant l'**UNIX way**, afin que les nouveaux gophers puissent rapidement entrer dans le monde de Go, avec un accueil chaleureux, de confiance.
130 |
131 | Fiber est **inspiré** par Express, le framework web le plus populaire d'Internet. Nous avons combiné la **facilité** d'Express, et la **performance brute** de Go. Si vous avez déja développé une application web en Node.js (_en utilisant Express ou équivalent_), alors de nombreuses méthodes et principes vous sembleront **familiers**.
132 |
133 | ## 👀 Exemples
134 |
135 | Ci-dessous quelques exemples courants. Si vous voulez voir plus d'exemples, rendez-vous sur notre ["Recipes repository"](https://github.com/gofiber/recipes) ou visitez notre [documentation API](https://fiber.wiki).
136 |
137 | ### Routing
138 |
139 | 📖 https://fiber.wiki/#basic-routing
140 |
141 |
142 | ```go
143 | func main() {
144 | app := fiber.New()
145 |
146 | // GET /john
147 | app.Get("/:name", func(c *fiber.Ctx) {
148 | fmt.Printf("Hello %s!", c.Params("name"))
149 | // => Hello john!
150 | })
151 |
152 | // GET /john
153 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
154 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
155 | // => Name: john, Age:
156 | })
157 |
158 | // GET /api/register
159 | app.Get("/api*", func(c *fiber.Ctx) {
160 | fmt.Printf("/api%s", c.Params("*"))
161 | // => /api/register
162 | })
163 |
164 | app.Listen(3000)
165 | }
166 | ```
167 |
168 | ### Serve static files
169 |
170 | 📖 https://fiber.wiki/application#static
171 |
172 | ```go
173 | func main() {
174 | app := fiber.New()
175 |
176 | app.Static("/", "/public")
177 | // => http://localhost:3000/js/script.js
178 | // => http://localhost:3000/css/style.css
179 |
180 | app.Static("/prefix", "/public")
181 | // => http://localhost:3000/prefix/js/script.js
182 | // => http://localhost:3000/prefix/css/style.css
183 |
184 | app.Static("*", "/public/index.html")
185 | // => http://localhost:3000/any/path/shows/index/html
186 |
187 | app.Listen(3000)
188 | }
189 | ```
190 |
191 | ### Middleware & Next
192 |
193 | 📖 https://fiber.wiki/routing#middleware
194 | 📖 https://fiber.wiki/context#next
195 |
196 | ```go
197 | func main() {
198 | app := fiber.New()
199 |
200 | // Match any route
201 | app.Use(func(c *fiber.Ctx) {
202 | fmt.Println("First middleware")
203 | c.Next()
204 | })
205 |
206 | // Match all routes starting with /api
207 | app.Use("/api", func(c *fiber.Ctx) {
208 | fmt.Println("Second middleware")
209 | c.Next()
210 | })
211 |
212 | // GET /api/register
213 | app.Get("/api/list", func(c *fiber.Ctx) {
214 | fmt.Println("Last middleware")
215 | c.Send("Hello, World!")
216 | })
217 |
218 | app.Listen(3000)
219 | }
220 | ```
221 |
222 |
223 | 📚 Show more code examples
224 |
225 | ### Template engines
226 |
227 | 📖 https://fiber.wiki/application#settings
228 | 📖 https://fiber.wiki/context#render
229 | 📖 https://fiber.wiki/middleware#template
230 |
231 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
232 |
233 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
234 |
235 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
236 |
237 | ```go
238 | package main
239 |
240 | import (
241 | "github.com/gofiber/fiber"
242 | "github.com/gofiber/template"
243 | )
244 |
245 | func main() {
246 | // You can setup template engine before initiation app:
247 | app := fiber.New(&fiber.Settings{
248 | TemplateEngine: template.Mustache(),
249 | TemplateFolder: "./views",
250 | TemplateExtension: ".tmpl",
251 | })
252 |
253 | // OR after initiation app at any convenient location:
254 | app.Settings.TemplateEngine = template.Mustache()
255 | app.Settings.TemplateFolder = "./views"
256 | app.Settings.TemplateExtension = ".tmpl"
257 |
258 | // And now, you can call template `./views/home.tmpl` like this:
259 | app.Get("/", func(c *fiber.Ctx) {
260 | c.Render("home", fiber.Map{
261 | "title": "Homepage",
262 | "year": 1999,
263 | })
264 | })
265 |
266 | // ...
267 | }
268 | ```
269 |
270 | ### Grouping routes into chains
271 |
272 | 📖 https://fiber.wiki/application#group
273 |
274 | ```go
275 | func main() {
276 | app := fiber.New()
277 |
278 | // Root API route
279 | api := app.Group("/api", cors()) // /api
280 |
281 | // API v1 routes
282 | v1 := api.Group("/v1", mysql()) // /api/v1
283 | v1.Get("/list", handler) // /api/v1/list
284 | v1.Get("/user", handler) // /api/v1/user
285 |
286 | // API v2 routes
287 | v2 := api.Group("/v2", mongodb()) // /api/v2
288 | v2.Get("/list", handler) // /api/v2/list
289 | v2.Get("/user", handler) // /api/v2/user
290 |
291 | // ...
292 | }
293 | ```
294 |
295 | ### Middleware logger
296 |
297 | 📖 https://fiber.wiki/middleware#logger
298 |
299 | ```go
300 | import (
301 | "github.com/gofiber/fiber"
302 | "github.com/gofiber/logger"
303 | )
304 |
305 | func main() {
306 | app := fiber.New()
307 |
308 | // Optional logger config
309 | config := logger.Config{
310 | Format: "${time} - ${method} ${path}\n",
311 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
312 | }
313 |
314 | // Logger with config
315 | app.Use(logger.New(config))
316 |
317 | app.Listen(3000)
318 | }
319 | ```
320 |
321 | ### Cross-Origin Resource Sharing (CORS)
322 |
323 | 📖 https://fiber.wiki/middleware#cors
324 |
325 | ```go
326 | import (
327 | "github.com/gofiber/fiber"
328 | "github.com/gofiber/cors"
329 | )
330 |
331 | func main() {
332 | app := fiber.New()
333 |
334 | // CORS with default config
335 | app.Use(cors.New())
336 |
337 | app.Listen(3000)
338 | }
339 | ```
340 |
341 | Check CORS by passing any domain in `Origin` header:
342 |
343 | ```bash
344 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
345 | ```
346 |
347 | ### Custom 404 response
348 |
349 | 📖 https://fiber.wiki/application#http-methods
350 |
351 | ```go
352 | func main() {
353 | app := fiber.New()
354 |
355 | app.Static("/public")
356 |
357 | app.Get("/demo", func(c *fiber.Ctx) {
358 | c.Send("This is a demo!")
359 | })
360 |
361 | app.Post("/register", func(c *fiber.Ctx) {
362 | c.Send("Welcome!")
363 | })
364 |
365 | // Last middleware to match anything
366 | app.Use(func(c *fiber.Ctx) {
367 | c.SendStatus(404)
368 | // => 404 "Not Found"
369 | })
370 |
371 | app.Listen(3000)
372 | }
373 | ```
374 |
375 | ### JSON Response
376 |
377 | 📖 https://fiber.wiki/context#json
378 |
379 | ```go
380 | type User struct {
381 | Name string `json:"name"`
382 | Age int `json:"age"`
383 | }
384 |
385 | func main() {
386 | app := fiber.New()
387 |
388 | app.Get("/user", func(c *fiber.Ctx) {
389 | c.JSON(&User{"John", 20})
390 | // => {"name":"John", "age":20}
391 | })
392 |
393 | app.Get("/json", func(c *fiber.Ctx) {
394 | c.JSON(fiber.Map{
395 | "success": true,
396 | "message": "Hi John!",
397 | })
398 | // => {"success":true, "message":"Hi John!"}
399 | })
400 |
401 | app.Listen(3000)
402 | }
403 | ```
404 |
405 | ### WebSocket Upgrade
406 |
407 | 📖 https://fiber.wiki/middleware#websocket
408 |
409 | ```go
410 | import (
411 | "github.com/gofiber/fiber"
412 | "github.com/gofiber/websocket"
413 | )
414 |
415 | func main() {
416 | app := fiber.New()
417 |
418 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
419 | for {
420 | mt, msg, err := c.ReadMessage()
421 | if err != nil {
422 | log.Println("read:", err)
423 | break
424 | }
425 | log.Printf("recv: %s", msg)
426 | err = c.WriteMessage(mt, msg)
427 | if err != nil {
428 | log.Println("write:", err)
429 | break
430 | }
431 | }
432 | }))
433 |
434 | app.Listen(3000)
435 | // ws://localhost:3000/ws
436 | }
437 | ```
438 |
439 | ### Recover middleware
440 |
441 | 📖 https://fiber.wiki/middleware#recover
442 |
443 | ```go
444 | import (
445 | "github.com/gofiber/fiber"
446 | "github.com/gofiber/recover"
447 | )
448 |
449 | func main() {
450 | app := fiber.New()
451 |
452 | // Optional recover config
453 | config := recover.Config{
454 | Handler: func(c *fiber.Ctx, err error) {
455 | c.SendString(err.Error())
456 | c.SendStatus(500)
457 | },
458 | }
459 |
460 | // Logger with custom config
461 | app.Use(recover.New(config))
462 |
463 | app.Listen(3000)
464 | }
465 | ```
466 |
467 |
468 | ## 💬 Media
469 |
470 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
471 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
472 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
473 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
474 |
475 | ## 👍 Contribuer
476 |
477 | Si vous voulez nous remercier et/ou soutenir le développement actif de `Fiber`:
478 |
479 | 1. Ajoutez une [GitHub Star](https://github.com/gofiber/fiber/stargazers) à ce projet.
480 | 2. Twittez à propos de ce projet [sur votre Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
481 | 3. Ecrivez un article (review, tutorial) sur [Medium](https://medium.com/), [Dev.to](https://dev.to/), ou encore un blog personnel.
482 | 4. Aidez nous à traduire ce `README` dans d'autres langages.
483 |
484 | ## ☕ Coffee Supporters
485 |
486 |
532 |
533 |
534 |
535 |
536 |
537 | ## 💻 Code Contributors
538 |
539 |
540 |
541 | ## ⚠️ License
542 |
543 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
544 |
--------------------------------------------------------------------------------
/.github/README_es.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber es un framework web inspirado en Express construido sobre Fasthttp, el motor HTTP más rápido para Go. Diseñado para facilitar las cosas para un desarrollo rápido con cero asignación de memoria y rendimiento en mente.
73 |
74 |
75 | ## ⚡️ Inicio rápido
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Hello, World!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ Instalación
94 |
95 | En primer lugar, [descargue](https://golang.org/dl/) e instale Go. Se requiere `1.11` o superior.
96 |
97 | La instalación se realiza con el comando [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) :
98 |
99 | ```bash
100 | go get github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 Puntos de referencia
104 |
105 | Estas pruebas son realizadas por [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) y [Go Web](https://github.com/smallnest/go-web-framework-benchmark) . Si desea ver todos los resultados, visite nuestro [Wiki](https://fiber.wiki/benchmarks) .
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 Características
113 |
114 | - [Enrutamiento](https://fiber.wiki/routing) robusto
115 | - Servir [archivos estáticos](https://fiber.wiki/application#static)
116 | - [Rendimiento](https://fiber.wiki/benchmarks) extremo
117 | - [Poca](https://fiber.wiki/benchmarks) huella de [memoria](https://fiber.wiki/benchmarks)
118 | - [Puntos finales de API](https://fiber.wiki/context) Express
119 | - Middleware y [próximo](https://fiber.wiki/context#next) soporte
120 | - Programación [rápida](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) del lado del servidor
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - Y mucho más, [explore Fiber](https://fiber.wiki/)
126 |
127 | ## 💡 Filosofía
128 |
129 | Los nuevos gophers que hacen el cambio de [Node.js](https://nodejs.org/en/about/) a [Go](https://golang.org/doc/) están lidiando con una curva de aprendizaje antes de que puedan comenzar a construir sus aplicaciones web o microservicios. Fiber, como un **marco web** , fue creado con la idea del **minimalismo** y sigue el **camino de UNIX** , para que los nuevos gophers puedan ingresar rápidamente al mundo de Go con una cálida y confiable bienvenida.
130 |
131 | Fiber está **inspirado** en Expressjs, el framework web más popular en Internet. Combinamos la **facilidad** de Express y **el rendimiento bruto** de Go. Si alguna vez ha implementado una aplicación web en Node.js ( *utilizando Express.js o similar* ), muchos métodos y principios le parecerán **muy comunes** .
132 |
133 | ## 👀 Ejemplos
134 |
135 | A continuación se enumeran algunos de los ejemplos comunes. Si desea ver más ejemplos de código, visite nuestro [repositorio de Recetas](https://github.com/gofiber/recipes) o nuestra [documentación de API](https://fiber.wiki) .
136 |
137 | ### Routing
138 |
139 | 📖 https://fiber.wiki/#basic-routing
140 |
141 |
142 | ```go
143 | func main() {
144 | app := fiber.New()
145 |
146 | // GET /john
147 | app.Get("/:name", func(c *fiber.Ctx) {
148 | fmt.Printf("Hello %s!", c.Params("name"))
149 | // => Hello john!
150 | })
151 |
152 | // GET /john
153 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
154 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
155 | // => Name: john, Age:
156 | })
157 |
158 | // GET /api/register
159 | app.Get("/api*", func(c *fiber.Ctx) {
160 | fmt.Printf("/api%s", c.Params("*"))
161 | // => /api/register
162 | })
163 |
164 | app.Listen(3000)
165 | }
166 | ```
167 |
168 | ### Serve static files
169 |
170 | 📖 https://fiber.wiki/application#static
171 |
172 | ```go
173 | func main() {
174 | app := fiber.New()
175 |
176 | app.Static("/", "/public")
177 | // => http://localhost:3000/js/script.js
178 | // => http://localhost:3000/css/style.css
179 |
180 | app.Static("/prefix", "/public")
181 | // => http://localhost:3000/prefix/js/script.js
182 | // => http://localhost:3000/prefix/css/style.css
183 |
184 | app.Static("*", "/public/index.html")
185 | // => http://localhost:3000/any/path/shows/index/html
186 |
187 | app.Listen(3000)
188 | }
189 | ```
190 |
191 | ### Middleware & Next
192 |
193 | 📖 https://fiber.wiki/routing#middleware
194 | 📖 https://fiber.wiki/context#next
195 |
196 | ```go
197 | func main() {
198 | app := fiber.New()
199 |
200 | // Match any route
201 | app.Use(func(c *fiber.Ctx) {
202 | fmt.Println("First middleware")
203 | c.Next()
204 | })
205 |
206 | // Match all routes starting with /api
207 | app.Use("/api", func(c *fiber.Ctx) {
208 | fmt.Println("Second middleware")
209 | c.Next()
210 | })
211 |
212 | // GET /api/register
213 | app.Get("/api/list", func(c *fiber.Ctx) {
214 | fmt.Println("Last middleware")
215 | c.Send("Hello, World!")
216 | })
217 |
218 | app.Listen(3000)
219 | }
220 | ```
221 |
222 |
223 | 📚 Show more code examples
224 |
225 | ### Template engines
226 |
227 | 📖 https://fiber.wiki/application#settings
228 | 📖 https://fiber.wiki/context#render
229 | 📖 https://fiber.wiki/middleware#template
230 |
231 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
232 |
233 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
234 |
235 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
236 |
237 | ```go
238 | package main
239 |
240 | import (
241 | "github.com/gofiber/fiber"
242 | "github.com/gofiber/template"
243 | )
244 |
245 | func main() {
246 | // You can setup template engine before initiation app:
247 | app := fiber.New(&fiber.Settings{
248 | TemplateEngine: template.Mustache(),
249 | TemplateFolder: "./views",
250 | TemplateExtension: ".tmpl",
251 | })
252 |
253 | // OR after initiation app at any convenient location:
254 | app.Settings.TemplateEngine = template.Mustache()
255 | app.Settings.TemplateFolder = "./views"
256 | app.Settings.TemplateExtension = ".tmpl"
257 |
258 | // And now, you can call template `./views/home.tmpl` like this:
259 | app.Get("/", func(c *fiber.Ctx) {
260 | c.Render("home", fiber.Map{
261 | "title": "Homepage",
262 | "year": 1999,
263 | })
264 | })
265 |
266 | // ...
267 | }
268 | ```
269 |
270 | ### Grouping routes into chains
271 |
272 | 📖 https://fiber.wiki/application#group
273 |
274 | ```go
275 | func main() {
276 | app := fiber.New()
277 |
278 | // Root API route
279 | api := app.Group("/api", cors()) // /api
280 |
281 | // API v1 routes
282 | v1 := api.Group("/v1", mysql()) // /api/v1
283 | v1.Get("/list", handler) // /api/v1/list
284 | v1.Get("/user", handler) // /api/v1/user
285 |
286 | // API v2 routes
287 | v2 := api.Group("/v2", mongodb()) // /api/v2
288 | v2.Get("/list", handler) // /api/v2/list
289 | v2.Get("/user", handler) // /api/v2/user
290 |
291 | // ...
292 | }
293 | ```
294 |
295 | ### Middleware logger
296 |
297 | 📖 https://fiber.wiki/middleware#logger
298 |
299 | ```go
300 | import (
301 | "github.com/gofiber/fiber"
302 | "github.com/gofiber/logger"
303 | )
304 |
305 | func main() {
306 | app := fiber.New()
307 |
308 | // Optional logger config
309 | config := logger.Config{
310 | Format: "${time} - ${method} ${path}\n",
311 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
312 | }
313 |
314 | // Logger with config
315 | app.Use(logger.New(config))
316 |
317 | app.Listen(3000)
318 | }
319 | ```
320 |
321 | ### Cross-Origin Resource Sharing (CORS)
322 |
323 | 📖 https://fiber.wiki/middleware#cors
324 |
325 | ```go
326 | import (
327 | "github.com/gofiber/fiber"
328 | "github.com/gofiber/cors"
329 | )
330 |
331 | func main() {
332 | app := fiber.New()
333 |
334 | // CORS with default config
335 | app.Use(cors.New())
336 |
337 | app.Listen(3000)
338 | }
339 | ```
340 |
341 | Check CORS by passing any domain in `Origin` header:
342 |
343 | ```bash
344 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
345 | ```
346 |
347 | ### Custom 404 response
348 |
349 | 📖 https://fiber.wiki/application#http-methods
350 |
351 | ```go
352 | func main() {
353 | app := fiber.New()
354 |
355 | app.Static("/public")
356 |
357 | app.Get("/demo", func(c *fiber.Ctx) {
358 | c.Send("This is a demo!")
359 | })
360 |
361 | app.Post("/register", func(c *fiber.Ctx) {
362 | c.Send("Welcome!")
363 | })
364 |
365 | // Last middleware to match anything
366 | app.Use(func(c *fiber.Ctx) {
367 | c.SendStatus(404)
368 | // => 404 "Not Found"
369 | })
370 |
371 | app.Listen(3000)
372 | }
373 | ```
374 |
375 | ### JSON Response
376 |
377 | 📖 https://fiber.wiki/context#json
378 |
379 | ```go
380 | type User struct {
381 | Name string `json:"name"`
382 | Age int `json:"age"`
383 | }
384 |
385 | func main() {
386 | app := fiber.New()
387 |
388 | app.Get("/user", func(c *fiber.Ctx) {
389 | c.JSON(&User{"John", 20})
390 | // => {"name":"John", "age":20}
391 | })
392 |
393 | app.Get("/json", func(c *fiber.Ctx) {
394 | c.JSON(fiber.Map{
395 | "success": true,
396 | "message": "Hi John!",
397 | })
398 | // => {"success":true, "message":"Hi John!"}
399 | })
400 |
401 | app.Listen(3000)
402 | }
403 | ```
404 |
405 | ### WebSocket Upgrade
406 |
407 | 📖 https://fiber.wiki/middleware#websocket
408 |
409 | ```go
410 | import (
411 | "github.com/gofiber/fiber"
412 | "github.com/gofiber/websocket"
413 | )
414 |
415 | func main() {
416 | app := fiber.New()
417 |
418 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
419 | for {
420 | mt, msg, err := c.ReadMessage()
421 | if err != nil {
422 | log.Println("read:", err)
423 | break
424 | }
425 | log.Printf("recv: %s", msg)
426 | err = c.WriteMessage(mt, msg)
427 | if err != nil {
428 | log.Println("write:", err)
429 | break
430 | }
431 | }
432 | }))
433 |
434 | app.Listen(3000)
435 | // ws://localhost:3000/ws
436 | }
437 | ```
438 |
439 | ### Recover middleware
440 |
441 | 📖 https://fiber.wiki/middleware#recover
442 |
443 | ```go
444 | import (
445 | "github.com/gofiber/fiber"
446 | "github.com/gofiber/recover"
447 | )
448 |
449 | func main() {
450 | app := fiber.New()
451 |
452 | // Optional recover config
453 | config := recover.Config{
454 | Handler: func(c *fiber.Ctx, err error) {
455 | c.SendString(err.Error())
456 | c.SendStatus(500)
457 | },
458 | }
459 |
460 | // Logger with custom config
461 | app.Use(recover.New(config))
462 |
463 | app.Listen(3000)
464 | }
465 | ```
466 |
467 |
468 | ## 💬 Medios
469 |
470 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
471 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
472 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
473 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
474 |
475 | ## 👍 Contribuir
476 |
477 | Si quiere **agradecer** y/o apoyar el desarrollo activo de la `Fiber`:
478 |
479 | 1. Agregue una [estrella de GitHub](https://github.com/gofiber/fiber/stargazers) al proyecto.
480 | 2. Tuitea sobre el proyecto [en tu Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
481 | 3. Escriba una reseña o tutorial en [Medium](https://medium.com/) , [Dev.to](https://dev.to/) o blog personal.
482 | 4. Ayúdanos a traducir este `README` y [API Docs](https://fiber.wiki/) a otro idioma.
483 |
484 | ## ☕ Coffee Supporters
485 |
486 |
532 |
533 |
534 |
535 |
536 |
537 | ## 💻 Code Contributors
538 |
539 |
540 |
541 | ## ⚠️ License
542 |
543 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
544 |
--------------------------------------------------------------------------------
/.github/README_id.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Fiber adalah web framework yang terinspirasi dari Express yang berbasiskan Fasthttp, HTTP engine paling cepat untuk Go. Dirancang untuk mempermudah, mempercepat pengembangan aplikasi dengan alokasi memori nol-nya serta kinerja yang selalu diperhatikan.
73 |
74 |
75 | ## ⚡️ Cara Mulai
76 |
77 | ```go
78 | package main
79 |
80 | import "github.com/gofiber/fiber"
81 |
82 | func main() {
83 | app := fiber.New()
84 |
85 | app.Get("/", func(c *fiber.Ctx) {
86 | c.Send("Hello, World!")
87 | })
88 |
89 | app.Listen(3000)
90 | }
91 | ```
92 |
93 | ## ⚙️ Instalasi
94 |
95 | Pertama, [unduh](https://golang.org/dl/) dan instal Go di komputer anda. Versi `1.11` atau yang lebih tinggi diperlukan.
96 |
97 | Instalasi dilakukkan dengan perintah [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them):
98 |
99 | ```bash
100 | go get -u github.com/gofiber/fiber/...
101 | ```
102 |
103 | ## 🤖 Pengukuran Kinerja
104 |
105 | Pengukuran ini dilakukan oleh [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) dan [Go Web](https://github.com/smallnest/go-web-framework-benchmark). Apabila anda ingin melihat hasil lengkapnya, silahkan kunjungi halaman [Wiki](https://fiber.wiki/benchmarks) kami.
106 |
107 |
108 |
109 |
110 |
111 |
112 | ## 🎯 Fitur
113 |
114 | - Sistem [Routing](https://fiber.wiki/routing) yang solid
115 | - Serve [file statis](https://fiber.wiki/application#static)
116 | - [Kinerja](https://fiber.wiki/benchmarks) ekstrim
117 | - [Penggunaan memori](https://fiber.wiki/benchmarks) yang kecil
118 | - Cocok untuk [API](https://fiber.wiki/context)
119 | - Mendukung Middleware & [Next](https://fiber.wiki/context#next) seperti Express
120 | - Kembangkan aplikasi dengan [Cepat](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497)
121 | - [Template engines](https://fiber.wiki/middleware#template)
122 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
123 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
124 | - Available in [10 languages](https://fiber.wiki/)
125 | - Dan masih banyak lagi, [kunjungi Fiber](https://fiber.wiki/)
126 |
127 | ## 💡 Filosofi
128 |
129 | Bagi yang baru yang beralih dari [Node.js](https://nodejs.org/en/about/) ke [Go](https://golang.org/doc/) terkadang perlu waktu yang cukup lama sebelum mereka mampu membuat aplikasi web dengan Go. Fiber, sebagai **web framework** dirancang secara **minimalis** dan mengikuti filosofi dari **UNIX**, sehingga pengguna baru dengan cepat memasuki dunia Go dengan sambutan yang hangat dan dapat diandalkan.
130 |
131 | Fiber terinspirasi dari Express, salah satu web framework paling terkenal di Internet. Kami menggabungkan **kemudahan** dari Express dan **kinerja luar biasa** dari Go. Apabila anda pernah membuat aplikasi dengan Node.js (_dengan Express atau yang lainnya_), maka banyak metode dan prinsip yang akan terasa **sangat umum** bagi anda.
132 |
133 | Kami **mendengarkan** para pengguna di [GitHub Issues](https://github.com/gofiber/fiber/issues) (_dan berbagai platform lainnya_) untuk menciptakan web framework yang **cepat**, **fleksibel** dan **bersahabat** untuk berbagai macam keperluan, **tenggat waktu** dan **keahlian** para pengguna! Sama halnya seperti yang dilakukkan Express di dunia JavaScript.
134 |
135 | ## 👀 Contoh
136 |
137 | Dibawah ini terdapat beberapa contoh penggunaan. Jika anda ingin contoh lainnya, silahkan kunjungi [Gudang resep](https://github.com/gofiber/recipes) atau kunjungi [Dokumentasi API](https://fiber.wiki) kami.
138 |
139 | ### Routing
140 |
141 | 📖 https://fiber.wiki/#basic-routing
142 |
143 |
144 | ```go
145 | func main() {
146 | app := fiber.New()
147 |
148 | // GET /john
149 | app.Get("/:name", func(c *fiber.Ctx) {
150 | fmt.Printf("Hello %s!", c.Params("name"))
151 | // => Hello john!
152 | })
153 |
154 | // GET /john
155 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
156 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
157 | // => Name: john, Age:
158 | })
159 |
160 | // GET /api/register
161 | app.Get("/api*", func(c *fiber.Ctx) {
162 | fmt.Printf("/api%s", c.Params("*"))
163 | // => /api/register
164 | })
165 |
166 | app.Listen(3000)
167 | }
168 | ```
169 |
170 | ### Serve static files
171 |
172 | 📖 https://fiber.wiki/application#static
173 |
174 | ```go
175 | func main() {
176 | app := fiber.New()
177 |
178 | app.Static("/", "/public")
179 | // => http://localhost:3000/js/script.js
180 | // => http://localhost:3000/css/style.css
181 |
182 | app.Static("/prefix", "/public")
183 | // => http://localhost:3000/prefix/js/script.js
184 | // => http://localhost:3000/prefix/css/style.css
185 |
186 | app.Static("*", "/public/index.html")
187 | // => http://localhost:3000/any/path/shows/index/html
188 |
189 | app.Listen(3000)
190 | }
191 | ```
192 |
193 | ### Middleware & Next
194 |
195 | 📖 https://fiber.wiki/routing#middleware
196 | 📖 https://fiber.wiki/context#next
197 |
198 | ```go
199 | func main() {
200 | app := fiber.New()
201 |
202 | // Match any route
203 | app.Use(func(c *fiber.Ctx) {
204 | fmt.Println("First middleware")
205 | c.Next()
206 | })
207 |
208 | // Match all routes starting with /api
209 | app.Use("/api", func(c *fiber.Ctx) {
210 | fmt.Println("Second middleware")
211 | c.Next()
212 | })
213 |
214 | // GET /api/register
215 | app.Get("/api/list", func(c *fiber.Ctx) {
216 | fmt.Println("Last middleware")
217 | c.Send("Hello, World!")
218 | })
219 |
220 | app.Listen(3000)
221 | }
222 | ```
223 |
224 |
225 | 📚 Show more code examples
226 |
227 | ### Template engines
228 |
229 | 📖 https://fiber.wiki/application#settings
230 | 📖 https://fiber.wiki/context#render
231 | 📖 https://fiber.wiki/middleware#template
232 |
233 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
234 |
235 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
236 |
237 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
238 |
239 | ```go
240 | package main
241 |
242 | import (
243 | "github.com/gofiber/fiber"
244 | "github.com/gofiber/template"
245 | )
246 |
247 | func main() {
248 | // You can setup template engine before initiation app:
249 | app := fiber.New(&fiber.Settings{
250 | TemplateEngine: template.Mustache(),
251 | TemplateFolder: "./views",
252 | TemplateExtension: ".tmpl",
253 | })
254 |
255 | // OR after initiation app at any convenient location:
256 | app.Settings.TemplateEngine = template.Mustache()
257 | app.Settings.TemplateFolder = "./views"
258 | app.Settings.TemplateExtension = ".tmpl"
259 |
260 | // And now, you can call template `./views/home.tmpl` like this:
261 | app.Get("/", func(c *fiber.Ctx) {
262 | c.Render("home", fiber.Map{
263 | "title": "Homepage",
264 | "year": 1999,
265 | })
266 | })
267 |
268 | // ...
269 | }
270 | ```
271 |
272 | ### Grouping routes into chains
273 |
274 | 📖 https://fiber.wiki/application#group
275 |
276 | ```go
277 | func main() {
278 | app := fiber.New()
279 |
280 | // Root API route
281 | api := app.Group("/api", cors()) // /api
282 |
283 | // API v1 routes
284 | v1 := api.Group("/v1", mysql()) // /api/v1
285 | v1.Get("/list", handler) // /api/v1/list
286 | v1.Get("/user", handler) // /api/v1/user
287 |
288 | // API v2 routes
289 | v2 := api.Group("/v2", mongodb()) // /api/v2
290 | v2.Get("/list", handler) // /api/v2/list
291 | v2.Get("/user", handler) // /api/v2/user
292 |
293 | // ...
294 | }
295 | ```
296 |
297 | ### Middleware logger
298 |
299 | 📖 https://fiber.wiki/middleware#logger
300 |
301 | ```go
302 | import (
303 | "github.com/gofiber/fiber"
304 | "github.com/gofiber/logger"
305 | )
306 |
307 | func main() {
308 | app := fiber.New()
309 |
310 | // Optional logger config
311 | config := logger.Config{
312 | Format: "${time} - ${method} ${path}\n",
313 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
314 | }
315 |
316 | // Logger with config
317 | app.Use(logger.New(config))
318 |
319 | app.Listen(3000)
320 | }
321 | ```
322 |
323 | ### Cross-Origin Resource Sharing (CORS)
324 |
325 | 📖 https://fiber.wiki/middleware#cors
326 |
327 | ```go
328 | import (
329 | "github.com/gofiber/fiber"
330 | "github.com/gofiber/cors"
331 | )
332 |
333 | func main() {
334 | app := fiber.New()
335 |
336 | // CORS with default config
337 | app.Use(cors.New())
338 |
339 | app.Listen(3000)
340 | }
341 | ```
342 |
343 | Check CORS by passing any domain in `Origin` header:
344 |
345 | ```bash
346 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
347 | ```
348 |
349 | ### Custom 404 response
350 |
351 | 📖 https://fiber.wiki/application#http-methods
352 |
353 | ```go
354 | func main() {
355 | app := fiber.New()
356 |
357 | app.Static("/public")
358 |
359 | app.Get("/demo", func(c *fiber.Ctx) {
360 | c.Send("This is a demo!")
361 | })
362 |
363 | app.Post("/register", func(c *fiber.Ctx) {
364 | c.Send("Welcome!")
365 | })
366 |
367 | // Last middleware to match anything
368 | app.Use(func(c *fiber.Ctx) {
369 | c.SendStatus(404)
370 | // => 404 "Not Found"
371 | })
372 |
373 | app.Listen(3000)
374 | }
375 | ```
376 |
377 | ### JSON Response
378 |
379 | 📖 https://fiber.wiki/context#json
380 |
381 | ```go
382 | type User struct {
383 | Name string `json:"name"`
384 | Age int `json:"age"`
385 | }
386 |
387 | func main() {
388 | app := fiber.New()
389 |
390 | app.Get("/user", func(c *fiber.Ctx) {
391 | c.JSON(&User{"John", 20})
392 | // => {"name":"John", "age":20}
393 | })
394 |
395 | app.Get("/json", func(c *fiber.Ctx) {
396 | c.JSON(fiber.Map{
397 | "success": true,
398 | "message": "Hi John!",
399 | })
400 | // => {"success":true, "message":"Hi John!"}
401 | })
402 |
403 | app.Listen(3000)
404 | }
405 | ```
406 |
407 | ### WebSocket Upgrade
408 |
409 | 📖 https://fiber.wiki/middleware#websocket
410 |
411 | ```go
412 | import (
413 | "github.com/gofiber/fiber"
414 | "github.com/gofiber/websocket"
415 | )
416 |
417 | func main() {
418 | app := fiber.New()
419 |
420 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
421 | for {
422 | mt, msg, err := c.ReadMessage()
423 | if err != nil {
424 | log.Println("read:", err)
425 | break
426 | }
427 | log.Printf("recv: %s", msg)
428 | err = c.WriteMessage(mt, msg)
429 | if err != nil {
430 | log.Println("write:", err)
431 | break
432 | }
433 | }
434 | }))
435 |
436 | app.Listen(3000)
437 | // ws://localhost:3000/ws
438 | }
439 | ```
440 |
441 | ### Recover middleware
442 |
443 | 📖 https://fiber.wiki/middleware#recover
444 |
445 | ```go
446 | import (
447 | "github.com/gofiber/fiber"
448 | "github.com/gofiber/recover"
449 | )
450 |
451 | func main() {
452 | app := fiber.New()
453 |
454 | // Optional recover config
455 | config := recover.Config{
456 | Handler: func(c *fiber.Ctx, err error) {
457 | c.SendString(err.Error())
458 | c.SendStatus(500)
459 | },
460 | }
461 |
462 | // Logger with custom config
463 | app.Use(recover.New(config))
464 |
465 | app.Listen(3000)
466 | }
467 | ```
468 |
469 |
470 | ## 💬 Media
471 |
472 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
473 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
474 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
475 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
476 |
477 | ## 👍 Berkontribusi
478 |
479 | Apabila anda ingin mengucapkan **terima kasih** dan/atau mendukung pengembangan `Fiber`:
480 |
481 | 1. Berikan bintang atau [GitHub Star](https://github.com/gofiber/fiber/stargazers) ke proyek ini.
482 | 2. Bagikan [di Twitter anda](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
483 | 3. Buat ulasan atau tutorial di [Medium](https://medium.com/), [Dev.to](https://dev.to/) atau blog pribadi anda.
484 | 4. Bantu kami menerjemahkan `README` ini ke bahasa lainnya.
485 |
486 |
487 | ## ☕ Coffee Para Pendukung
488 |
489 |
535 |
536 |
537 |
538 |
539 |
540 | ## 💻 Code Contributors
541 |
542 |
543 |
544 | ## ⚠️ License
545 |
546 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
547 |
--------------------------------------------------------------------------------
/.github/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.
70 |
71 |
72 | ## ⚡️ Quickstart
73 |
74 | ```go
75 | package main
76 |
77 | import "github.com/gofiber/fiber"
78 |
79 | func main() {
80 | app := fiber.New()
81 |
82 | app.Get("/", func(c *fiber.Ctx) {
83 | c.Send("Hello, World!")
84 | })
85 |
86 | app.Listen(3000)
87 | }
88 | ```
89 |
90 | ## ⚙️ Installation
91 |
92 | First of all, [download](https://golang.org/dl/) and install Go. `1.11` or higher is required.
93 |
94 | Installation is done using the [`go get`](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) command:
95 |
96 | ```bash
97 | go get -u github.com/gofiber/fiber
98 | ```
99 |
100 | ## 🤖 Benchmarks
101 |
102 | These tests are performed by [TechEmpower](https://github.com/TechEmpower/FrameworkBenchmarks) and [Go Web](https://github.com/smallnest/go-web-framework-benchmark). If you want to see all results, please visit our [Wiki](https://fiber.wiki/benchmarks).
103 |
104 |
105 |
106 |
107 |
108 |
109 | ## 🎯 Features
110 |
111 | - Robust [routing](https://fiber.wiki/routing)
112 | - Serve [static files](https://fiber.wiki/application#static)
113 | - Extreme [performance](https://fiber.wiki/benchmarks)
114 | - [Low memory](https://fiber.wiki/benchmarks) footprint
115 | - [API endpoints](https://fiber.wiki/context)
116 | - [Middleware](https://fiber.wiki/middleware) & [Next](https://fiber.wiki/context#next) support
117 | - [Rapid](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) server-side programming
118 | - [Template engines](https://fiber.wiki/middleware#template)
119 | - [WebSocket support](https://fiber.wiki/middleware#websocket)
120 | - [Rate Limiter](https://fiber.wiki/middleware#limiter)
121 | - Translated in 10 other languages
122 | - And much more, [explore Fiber](https://fiber.wiki/)
123 |
124 | ## 💡 Philosophy
125 |
126 | New gophers that make the switch from [Node.js](https://nodejs.org/en/about/) to [Go](https://golang.org/doc/) are dealing with a learning curve before they can start building their web applications or microservices. Fiber, as a **web framework**, was created with the idea of **minimalism** and follows the **UNIX way**, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.
127 |
128 | Fiber is **inspired** by Express, the most popular web framework on the Internet. We combined the **ease** of Express and **raw performance** of Go. If you have ever implemented a web application in Node.js (_using Express or similar_), then many methods and principles will seem **very common** to you.
129 |
130 | We **listen** to our users in [issues](https://github.com/gofiber/fiber/issues) (_and all over the Internet_) to create a **fast**, **flexible** and **friendly** Go web framework for **any** task, **deadline** and developer **skill**! Just like Express does in the JavaScript world.
131 |
132 | ## 👀 Examples
133 |
134 | Listed below are some of the common examples.
135 |
136 | > If you want to see more code examples, please visit our [Recipes repository](https://github.com/gofiber/recipes) or visit our [API documentation](https://fiber.wiki).
137 |
138 | ### Routing
139 |
140 | 📖 https://fiber.wiki/#basic-routing
141 |
142 |
143 | ```go
144 | func main() {
145 | app := fiber.New()
146 |
147 | // GET /john
148 | app.Get("/:name", func(c *fiber.Ctx) {
149 | fmt.Printf("Hello %s!", c.Params("name"))
150 | // => Hello john!
151 | })
152 |
153 | // GET /john
154 | app.Get("/:name/:age?", func(c *fiber.Ctx) {
155 | fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
156 | // => Name: john, Age:
157 | })
158 |
159 | // GET /api/register
160 | app.Get("/api*", func(c *fiber.Ctx) {
161 | fmt.Printf("/api%s", c.Params("*"))
162 | // => /api/register
163 | })
164 |
165 | app.Listen(3000)
166 | }
167 | ```
168 |
169 | ### Serve static files
170 |
171 | 📖 https://fiber.wiki/application#static
172 |
173 | ```go
174 | func main() {
175 | app := fiber.New()
176 |
177 | app.Static("/", "/public")
178 | // => http://localhost:3000/js/script.js
179 | // => http://localhost:3000/css/style.css
180 |
181 | app.Static("/prefix", "/public")
182 | // => http://localhost:3000/prefix/js/script.js
183 | // => http://localhost:3000/prefix/css/style.css
184 |
185 | app.Static("*", "/public/index.html")
186 | // => http://localhost:3000/any/path/shows/index/html
187 |
188 | app.Listen(3000)
189 | }
190 | ```
191 |
192 | ### Middleware & Next
193 |
194 | 📖 https://fiber.wiki/routing#middleware
195 | 📖 https://fiber.wiki/context#next
196 |
197 | ```go
198 | func main() {
199 | app := fiber.New()
200 |
201 | // Match any route
202 | app.Use(func(c *fiber.Ctx) {
203 | fmt.Println("First middleware")
204 | c.Next()
205 | })
206 |
207 | // Match all routes starting with /api
208 | app.Use("/api", func(c *fiber.Ctx) {
209 | fmt.Println("Second middleware")
210 | c.Next()
211 | })
212 |
213 | // GET /api/register
214 | app.Get("/api/list", func(c *fiber.Ctx) {
215 | fmt.Println("Last middleware")
216 | c.Send("Hello, World!")
217 | })
218 |
219 | app.Listen(3000)
220 | }
221 | ```
222 |
223 |
224 | 📚 Show more code examples
225 |
226 | ### Template engines
227 |
228 | 📖 https://fiber.wiki/application#settings
229 | 📖 https://fiber.wiki/context#render
230 | 📖 https://fiber.wiki/middleware#template
231 |
232 | Fiber supports the default [Go template engine](https://golang.org/pkg/html/template/)
233 |
234 | But if you want to use another template engine like [amber](https://github.com/eknkc/amber), [handlebars](https://github.com/aymerick/raymond), [mustache](https://github.com/cbroglie/mustache) or [pug](https://github.com/Joker/jade).
235 |
236 | You can use our [Template Middleware](https://fiber.wiki/middleware#template).
237 |
238 | ```go
239 | package main
240 |
241 | import (
242 | "github.com/gofiber/fiber"
243 | "github.com/gofiber/template"
244 | )
245 |
246 | func main() {
247 | // You can setup template engine before initiation app:
248 | app := fiber.New(&fiber.Settings{
249 | TemplateEngine: template.Mustache(),
250 | TemplateFolder: "./views",
251 | TemplateExtension: ".tmpl",
252 | })
253 |
254 | // OR after initiation app at any convenient location:
255 | app.Settings.TemplateEngine = template.Mustache()
256 | app.Settings.TemplateFolder = "./views"
257 | app.Settings.TemplateExtension = ".tmpl"
258 |
259 | // And now, you can call template `./views/home.tmpl` like this:
260 | app.Get("/", func(c *fiber.Ctx) {
261 | c.Render("home", fiber.Map{
262 | "title": "Homepage",
263 | "year": 1999,
264 | })
265 | })
266 |
267 | // ...
268 | }
269 | ```
270 |
271 | ### Grouping routes into chains
272 |
273 | 📖 https://fiber.wiki/application#group
274 |
275 | ```go
276 | func main() {
277 | app := fiber.New()
278 |
279 | // Root API route
280 | api := app.Group("/api", cors()) // /api
281 |
282 | // API v1 routes
283 | v1 := api.Group("/v1", mysql()) // /api/v1
284 | v1.Get("/list", handler) // /api/v1/list
285 | v1.Get("/user", handler) // /api/v1/user
286 |
287 | // API v2 routes
288 | v2 := api.Group("/v2", mongodb()) // /api/v2
289 | v2.Get("/list", handler) // /api/v2/list
290 | v2.Get("/user", handler) // /api/v2/user
291 |
292 | // ...
293 | }
294 | ```
295 |
296 | ### Middleware logger
297 |
298 | 📖 https://fiber.wiki/middleware#logger
299 |
300 | ```go
301 | import (
302 | "github.com/gofiber/fiber"
303 | "github.com/gofiber/logger"
304 | )
305 |
306 | func main() {
307 | app := fiber.New()
308 |
309 | // Optional logger config
310 | config := logger.Config{
311 | Format: "${time} - ${method} ${path}\n",
312 | TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
313 | }
314 |
315 | // Logger with config
316 | app.Use(logger.New(config))
317 |
318 | app.Listen(3000)
319 | }
320 | ```
321 |
322 | ### Cross-Origin Resource Sharing (CORS)
323 |
324 | 📖 https://fiber.wiki/middleware#cors
325 |
326 | ```go
327 | import (
328 | "github.com/gofiber/fiber"
329 | "github.com/gofiber/cors"
330 | )
331 |
332 | func main() {
333 | app := fiber.New()
334 |
335 | // CORS with default config
336 | app.Use(cors.New())
337 |
338 | app.Listen(3000)
339 | }
340 | ```
341 |
342 | Check CORS by passing any domain in `Origin` header:
343 |
344 | ```bash
345 | curl -H "Origin: http://example.com" --verbose http://localhost:3000
346 | ```
347 |
348 | ### Custom 404 response
349 |
350 | 📖 https://fiber.wiki/application#http-methods
351 |
352 | ```go
353 | func main() {
354 | app := fiber.New()
355 |
356 | app.Static("/public")
357 |
358 | app.Get("/demo", func(c *fiber.Ctx) {
359 | c.Send("This is a demo!")
360 | })
361 |
362 | app.Post("/register", func(c *fiber.Ctx) {
363 | c.Send("Welcome!")
364 | })
365 |
366 | // Last middleware to match anything
367 | app.Use(func(c *fiber.Ctx) {
368 | c.SendStatus(404)
369 | // => 404 "Not Found"
370 | })
371 |
372 | app.Listen(3000)
373 | }
374 | ```
375 |
376 | ### JSON Response
377 |
378 | 📖 https://fiber.wiki/context#json
379 |
380 | ```go
381 | type User struct {
382 | Name string `json:"name"`
383 | Age int `json:"age"`
384 | }
385 |
386 | func main() {
387 | app := fiber.New()
388 |
389 | app.Get("/user", func(c *fiber.Ctx) {
390 | c.JSON(&User{"John", 20})
391 | // => {"name":"John", "age":20}
392 | })
393 |
394 | app.Get("/json", func(c *fiber.Ctx) {
395 | c.JSON(fiber.Map{
396 | "success": true,
397 | "message": "Hi John!",
398 | })
399 | // => {"success":true, "message":"Hi John!"}
400 | })
401 |
402 | app.Listen(3000)
403 | }
404 | ```
405 |
406 | ### WebSocket Upgrade
407 |
408 | 📖 https://fiber.wiki/middleware#websocket
409 |
410 | ```go
411 | import (
412 | "github.com/gofiber/fiber"
413 | "github.com/gofiber/websocket"
414 | )
415 |
416 | func main() {
417 | app := fiber.New()
418 |
419 | app.Get("/ws", websocket.New(func(c *websocket.Conn) {
420 | for {
421 | mt, msg, err := c.ReadMessage()
422 | if err != nil {
423 | log.Println("read:", err)
424 | break
425 | }
426 | log.Printf("recv: %s", msg)
427 | err = c.WriteMessage(mt, msg)
428 | if err != nil {
429 | log.Println("write:", err)
430 | break
431 | }
432 | }
433 | }))
434 |
435 | app.Listen(3000)
436 | // ws://localhost:3000/ws
437 | }
438 | ```
439 |
440 | ### Recover middleware
441 |
442 | 📖 https://fiber.wiki/middleware#recover
443 |
444 | ```go
445 | import (
446 | "github.com/gofiber/fiber"
447 | "github.com/gofiber/recover"
448 | )
449 |
450 | func main() {
451 | app := fiber.New()
452 |
453 | // Optional recover config
454 | config := recover.Config{
455 | Handler: func(c *fiber.Ctx, err error) {
456 | c.SendString(err.Error())
457 | c.SendStatus(500)
458 | },
459 | }
460 |
461 | // Logger with custom config
462 | app.Use(recover.New(config))
463 |
464 | app.Listen(3000)
465 | }
466 | ```
467 |
468 |
469 | ## 🧬 Available Middlewares
470 |
471 | For _easier_ and _more clear_ work, we've put [middleware](https://fiber.wiki/middleware) into separate repositories:
472 |
473 | - [Basic Authentication](https://github.com/gofiber/basicauth)
474 | - [Key Authentication](https://github.com/gofiber/keyauth)
475 | - [Compression](https://github.com/gofiber/compression)
476 | - [Request ID](https://github.com/gofiber/requestid)
477 | - [WebSocket](https://github.com/gofiber/websocket)
478 | - [Rewrite](https://github.com/gofiber/rewrite)
479 | - [Recover](https://github.com/gofiber/recover)
480 | - [Limiter](https://github.com/gofiber/limiter)
481 | - [Session](https://github.com/gofiber/session)
482 | - [Logger](https://github.com/gofiber/logger)
483 | - [Helmet](https://github.com/gofiber/helmet)
484 | - [CORS](https://github.com/gofiber/cors)
485 | - [CSRF](https://github.com/gofiber/csrf)
486 | - [JWT](https://github.com/gofiber/jwt)
487 |
488 | ## 💬 Media
489 |
490 | - [Welcome to Fiber — an Express.js styled web framework written in Go with ❤️](https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497) - _03 Feb 2020_
491 | - [Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?](https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf) - _21 Feb 2020_
492 | - [🚀 Fiber v1.8. What's new, updated and re-thinked?](https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h) - _03 Mar 2020_
493 | - [Is switching from Express to Fiber worth it? 🤔](https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1) - _01 Apr 2020_
494 |
495 | ## 👍 Contribute
496 |
497 | If you want to say **thank you** and/or support the active development of `Fiber`:
498 |
499 | 1. Add a [GitHub Star](https://github.com/gofiber/fiber/stargazers) to the project.
500 | 2. Tweet about the project [on your Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20%E2%80%94%20is%20an%20Express.js%20inspired%20web%20framework%20build%20on%20Fasthttp%20for%20%23Go%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
501 | 3. Write a review or tutorial on [Medium](https://medium.com/), [Dev.to](https://dev.to/) or personal blog.
502 | 4. Help us to translate this `README` to another language.
503 |
504 |
505 | ## ☕ Coffee Supporters
506 |
507 |
553 |
554 |
555 |
556 |
557 |
558 | ## 💻 Code Contributors
559 |
560 |
561 |
562 | ## ⚠️ License
563 |
564 | Copyright (c) 2019-present [Fenny](https://github.com/fenny) and [Fiber Contributors](https://github.com/gofiber/fiber/graphs/contributors). `Fiber` is free and open-source software licensed under the [MIT License](https://github.com/gofiber/fiber/blob/master/LICENSE). Official logo was created by [Vic Shóstak](https://github.com/koddr) and distributed under [Creative Commons](https://creativecommons.org/licenses/by-sa/4.0/) license (CC BY-SA 4.0 International).
565 |
--------------------------------------------------------------------------------