Skip to content

Starter guide

Let’s start with the minimal example you may have seen on the front page:

package main

import "github.com/flamego/flamego"

func main() {
	f := flamego.Classic()
	f.Get("/", func() string {
		return "Hello, Flamego!"
	})
	f.Run()
}

On line 6, the function flamego.Classic creates and returns a classic Flame instance with a default list of middleware, including flamego.Logger, flamego.Recovery and flamego.Static.

On line 7, the method f.Get registers the anonymous function (from line 7 to 9) to be the handler of the root path ("/") when a HTTP GET request comes in. In this case, the handler simply responds with a “Hello, Flamego!” string to the client.

On line 10, we start the web server by calling f.Run. By default, the Flame instance listens on the address 0.0.0.0:2830.

Alright, now save the file and initialize a Go module:

$ mkdir flamego-example
$ cd flamego-example
$ nano main.go

$ go mod init flamego-example
go: creating new go.mod: module flamego-example
$ go mod tidy
go: finding module for package github.com/flamego/flamego
...

$ go run main.go
[Flamego] Listening on 0.0.0.0:2830 (development)

Once you see the last line from your terminal, you’re good to go!

You may verify the result by either visiting http://localhost:2830 (why 2830?) in your browser, or through the folllowing curl command:

$ curl http://localhost:2830
Hello, Flamego!

💡 Did you know?

If you have used other Go web frameworks like Gin or Echo, you may be surprised that you can directly return a string in Flamego handlers as the response body to the client.

That is exactly right! Of course, this won’t be the only way to make a response body (which would be a very unfriendly design!). If you’re interested in reading more, the return values is the magician behind the scene.

Unfolding hidden parts

The minimal example aims for the least lines of code for a functioning example, but it inevitably hides some interesting details. Therefore, we’re going to unfold those hidden parts to understand more about how things are assembled.

Let’s first modify our main.go file as follows:

package main

import (
	"log"
	"net/http"

	"github.com/flamego/flamego"
)

func main() {
	f := flamego.Classic()
	f.Get("/{*}", printRequestPath)

	log.Println("Server is running...")
	log.Println(http.ListenAndServe("0.0.0.0:2830", f))