Core services

To get you off the ground, Flamego provides some core services that are essential to almost all web applications. However, you are not required to use all of them. The design principle of Flamego is always building the minimal core and pluggable addons at your own choice.

Context

Every handler invocation comes with its own request context, which is represented as the type flamego.Context. Data and state are not shared among these request contexts, which makes handler invocations independent from each other unless your web application has defined some other shared resources (e.g. database connections, cache).

Thereforce, flamego.Context is available to use out-of-the-box by your handlers:

  1. func main() {
  2. f := flamego.New()
  3. f.Get("/", func(c flamego.Context) string {
  4. ...
  5. })
  6. f.Run()
  7. }

Next

When a route is matched by a request, the Flame instance queues a chain of handlers (including middleware) to be invoked in the same order as they are registered.

By default, the next handler will only be invoked after the previous one in the chain has finished. You may change this behvaior using the Next method, which allows you to pause the execution of the current handler and resume after the rest of the chain finished.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. f := flamego.New()
  8. f.Get("/",
  9. func(c flamego.Context) {
  10. fmt.Println("starting the first handler")
  11. c.Next()
  12. fmt.Println("exiting the first handler")
  13. },
  14. func() {
  15. fmt.Println("executing the second handler")
  16. },
  17. )
  18. f.Run()
  19. }

When you run the above program and do curl http://localhost:2830/, the following logs are printed to your terminal:

  1. [Flamego] Listening on 0.0.0.0:2830 (development)
  2. starting the first handler
  3. executing the second handler
  4. exiting the first handler

The routing logger is taking advantage of this feature to collect the duration and status code of requests.

Remote address

Web applications often want to know where clients are coming from, then the RemoteAddr() method is the convenient helper made for you:

  1. func main() {
  2. f := flamego.New()
  3. f.Get("/", func(c flamego.Context) string {
  4. return "The remote address is " + c.RemoteAddr()
  5. })
  6. f.Run()
  7. }

The RemoteAddr() method is smarter than the standard library that only looks at the http.Request.RemoteAddr field (which stops working if your web application is behind a reverse proxy), it also takes into consideration of some well-known headers.

This method looks at following things in the order to determine which one is more likely to contain the real client address:

  • The X-Real-IP request header
  • The X-Forwarded-For request header
  • The http.Request.RemoteAddr field

This way, you can configure your reverse proxy to pass on one of these headers.

::: warning The client can always fake its address using a proxy or VPN, getting the remote address is always considered as a best effort in web applications. :::

Redirect

The Redirect method is a shorthand for the http.Redirect given the fact that the request context knows what the http.ResponseWriter and *http.Request are for the current request, and uses the http.StatusFound as the default status code for the redirection:

:::: code-group ::: code-group-item Code

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. f := flamego.New()
  8. f.Get("/", func(c flamego.Context) {
  9. c.Redirect("/signup")
  10. })
  11. f.Get("/login", func(c flamego.Context) {
  12. c.Redirect("/signin", http.StatusMovedPermanently)
  13. })
  14. f.Run()
  15. }

::: ::: code-group-item Test

  1. $ curl -i http://localhost:2830/
  2. HTTP/1.1 302 Found
  3. ...
  4. $ curl -i http://localhost:2830/login
  5. HTTP/1.1 301 Moved Permanently
  6. ...

::: ::::

::: warning Be aware that the Redirect method does a naive redirection and is vulnerable to the open redirect vulnerability.

For example, the following is also works as a valid redirection:

  1. c.Redirect("https://www.google.com")

Please make sure to always first validating the user input! :::

URL parameters

URL parameters, also known as “URL query parameters”, or “URL query strings”, are commonly used to pass arguments to the backend for all HTTP methods (POST forms have to be sent with POST method, as the counterpart).

The Query method is built as a helper for accessing the URL parameters, and return an empty string if no such parameter found with the given key:

:::: code-group ::: code-group-item Code

  1. package main
  2. import (
  3. "github.com/flamego/flamego"
  4. )
  5. func main() {
  6. f := flamego.New()
  7. f.Get("/", func(c flamego.Context) string {
  8. return "The name is " + c.Query("name")
  9. })
  10. f.Run()
  11. }

::: ::: code-group-item Test

  1. $ curl http://localhost:2830?name=joe
  2. The name is joe
  3. $ curl http://localhost:2830
  4. The name is

::: ::::

There is a family of Query methods available at your fingertips, including:

  • QueryTrim trims spaces and returns value.
  • QueryStrings returns a list of strings.
  • QueryUnescape returns unescaped query result.
  • QueryBool returns value parsed as bool.
  • QueryInt returns value parsed as int.
  • QueryInt returns value parsed as int64.
  • QueryFloat64 returns value parsed as float64.

::: tip If you are not happy with the functionality that is provided by the family of Query methods, it is always possible to build your own helpers (or middlware) for the URL parameters by accessing the underlying url.Values directly:

  1. vals := c.Request().URL.Query()

:::

Is flamego.Context a replacement to context.Context?

No.

The flamego.Context is a representation of the request context and should live within the routing layer, where the context.Context is a general purpose context and can be propogated to almost anywhere (e.g. database layer).

You can retrieve the context.Context of a request using the following methods:

  1. f.Get(..., func(c flamego.Context) {
  2. ctx := c.Request().Context()
  3. ...
  4. })
  5. // or
  6. f.Get(..., func(r *http.Request) {
  7. ctx := r.Context()
  8. ...
  9. })

Default logger

The *log.Logger is available to all handers for general logging purposes, this is particularly useful if you’re writing middleware:

  1. package main
  2. import (
  3. "log"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. f := flamego.New()
  8. f.Get("/", func(log *log.Logger) {
  9. log.Println("Hello, Flamego!")
  10. })
  11. f.Run()
  12. }

When you run the above program and do curl http://localhost:2830/, the following logs are printed to your terminal:

  1. [Flamego] Listening on 0.0.0.0:2830 (development)
  2. [Flamego] Hello, Flamego!

The routing logger is taking advantage of this feature to print the duration and status code of requests.

Response stream

The response stream of a request is represented by the type http.ResponseWriter, you may use it as an argument of your handlers or through the ResponseWriter method of the flamego.Context:

  1. f.Get(..., func(w http.ResponseWriter) {
  2. ...
  3. })
  4. // or
  5. f.Get(..., func(c flamego.Context) {
  6. w := c.ResponseWriter()
  7. ...
  8. })

::: tip 💡 Did you know? Not all handlers that are registered for a route are always being invoked, the request context (flamego.Context) stops invoking subsequent handlers when the response status code has been written by the current handler. This is similar to how the short circuit evaluation works. :::

Request object

The request object is represented by the type *http.Request, you may use it as an argument of your handlers or through the Request().Request field of the flamego.Context:

  1. f.Get(..., func(r *http.Request) {
  2. ...
  3. })
  4. // or
  5. f.Get(..., func(c flamego.Context) {
  6. r := c.Request().Request
  7. ...
  8. })

You may wonder what does c.Request() return in the above example?

Good catch! It returns a thin wrapper of the *http.Request and has the type *flamego.Request, which provides helpers to read the request body:

  1. f.Get(..., func(c flamego.Context) {
  2. body := c.Request().Body().Bytes()
  3. ...
  4. })

Routing logger

::: tip This middleware is automatically registered when you use flamego.Classic to create a Flame instance. :::

The flamego.Logger is the middleware that provides logging of requested routes and corresponding status code:

  1. package main
  2. import (
  3. "github.com/flamego/flamego"
  4. )
  5. func main() {
  6. f := flamego.New()
  7. f.Use(flamego.Logger())
  8. f.Get("/", func() (int, error) {
  9. return http.StatusOK, nil
  10. })
  11. f.Run()
  12. }

When you run the above program and do curl http://localhost:2830/, the following logs are printed to your terminal:

  1. [Flamego] Listening on 0.0.0.0:2830 (development)
  2. [Flamego] ...: Started GET / for 127.0.0.1
  3. [Flamego] ...: Completed GET / 200 OK in 165.791µs

Panic recovery

::: tip This middleware is automatically registered when you use flamego.Classic to create a Flame instance. :::

The flamego.Recovery is the middleware that is for recovering from panic:

  1. package main
  2. import (
  3. "github.com/flamego/flamego"
  4. )
  5. func main() {
  6. f := flamego.New()
  7. f.Use(flamego.Recovery())
  8. f.Get("/", func() {
  9. panic("I can't breath")
  10. })
  11. f.Run()
  12. }

When you run the above program and visit http://localhost:2830/, the recovered page is displayed:

panic recovery

Serving static files

::: tip This middleware is automatically registered when you use flamego.Classic to create a Flame instance. :::

The flamego.Static is the middleware that is for serving static files, and it accepts an optional flamego.StaticOptions:

  1. func main() {
  2. f := flamego.New()
  3. f.Use(flamego.Static(
  4. flamego.StaticOptions{
  5. Directory: "public",
  6. },
  7. ))
  8. f.Run()
  9. }

You may also omit passing the options for using all default values:

  1. func main() {
  2. f := flamego.New()
  3. f.Use(flamego.Static())
  4. f.Run()
  5. }

Example: Serving the source file

In this example, we’re going to treat our source code file as the static resources:

  1. package main
  2. import (
  3. "github.com/flamego/flamego"
  4. )
  5. func main() {
  6. f := flamego.New()
  7. f.Use(flamego.Static(
  8. flamego.StaticOptions{
  9. Directory: "./",
  10. Index: "main.go",
  11. },
  12. ))
  13. f.Run()
  14. }

On line 11, we changed the Directory to be the working directory ("./") instead of the default value "public".

On line 12, we changed the index file (the file to be served when listing a directory) to be main.go instead of the default value "index.html".

When you save the above program as main.go and run it, both curl http://localhost:2830/ and curl http://localhost:2830/main.go will response the content of this main.go back to you.

Example: Serving multiple directories

In this example, we’re going to serve static resources for two different directories.

Here is the setup for the example:

:::: code-group ::: code-group-item Directory

  1. $ tree .
  2. .
  3. ├── css
  4. └── main.css
  5. ├── go.mod
  6. ├── go.sum
  7. ├── js
  8. └── main.js
  9. └── main.go
  10. 2 directories, 5 files

::: ::: code-group-item css/main.css

  1. html {
  2. color: red;
  3. }

::: ::: code-group-item js/main.js

  1. console.log("Hello, Flamego!");

::: ::: code-group-item main.go

  1. package main
  2. import (
  3. "github.com/flamego/flamego"
  4. )
  5. func main() {
  6. f := flamego.New()
  7. f.Use(flamego.Static(
  8. flamego.StaticOptions{
  9. Directory: "js",
  10. },
  11. ))
  12. f.Use(flamego.Static(
  13. flamego.StaticOptions{
  14. Directory: "css",
  15. },
  16. ))
  17. f.Run()
  18. }

::: ::: code-group-item Test

  1. $ curl http://localhost:2830/main.css
  2. html {
  3. color: red;
  4. }
  5. $ curl http://localhost:2830/main.js
  6. console.log("Hello, Flamego!");

::: ::::

You may have noticed that the client should not include the value of Directory, which are "css" and "js" in the example. If you would like the client to include these values, you can use the Prefix option:

  1. f.Use(flamego.Static(
  2. flamego.StaticOptions{
  3. Directory: "css",
  4. Prefix: "css",
  5. },
  6. ))

::: tip 💡 Did you know? The value of Prefix does not have to be the same as the value of Directory. :::

Example: Serving the embed.FS

In this example, we’re going to serve static resources from the embed.FS that was introduced in Go 1.16.

Here is the setup for the example:

:::: code-group ::: code-group-item Directory

  1. tree .
  2. .
  3. ├── css
  4. └── main.css
  5. ├── go.mod
  6. ├── go.sum
  7. └── main.go
  8. 1 directory, 4 files

::: ::: code-group-item css/main.css

  1. html {
  2. color: red;
  3. }

::: ::: code-group-item main.go

  1. package main
  2. import (
  3. "embed"
  4. "net/http"
  5. "github.com/flamego/flamego"
  6. )
  7. //go:embed css
  8. var css embed.FS
  9. func main() {
  10. f := flamego.New()
  11. f.Use(flamego.Static(
  12. flamego.StaticOptions{
  13. FileSystem: http.FS(css),
  14. },
  15. ))
  16. f.Run()
  17. }

::: ::: code-group-item Test

  1. $ curl http://localhost:2830/css/main.css
  2. html {
  3. color: red;
  4. }

::: ::::

::: warning Because the Go embed encodes the entire path (i.e. including parent directories), the client have to use the full path, which is different from serving static files directly from the local disk.

In other words, the following command will not work for the example:

  1. $ curl http://localhost:2830/main.css
  2. 404 page not found

:::