Starter Guide
Before we get started, one thing you should know is that this documentation does not teach you how to use Go. Instead, we will explore Macaron based on the basic Go knowledge you already have.
To install Macaron:
And upgrade Macaron in the future:
Minimal Example
Create a file called main.go
, and type following code:
Function macaron.Classic
creates and returns a Classic Macaron.
Method m.Get
is for registering routes for HTTP GET method. In this case, we allow GET requests to root path /
and has a Handler function to simply returns string Hello world!
as response.
You may have questions about why the handler function can return a string as response? The magic is the Return Values, this is a special case/syntax for responding requests by string.
Finally, we call method m.Run
to get server running. By default, Macaron Instances will listen on 0.0.0.0:4000
.
Then, execute command go run main.go
, you should see a log message is printed to the console:
Now, open your browser and visit localhost:4000, victory!
Extended Example
Let’s modify the main.go
and do some extended exercises.
If you execute command go run main.go
again, you’ll see string the request path is: /
is on your screen.
So what’s different now?
First of all, we still use Classic Macaron and register route for HTTP GET method of root path /
. We don’t use anonymous function anymore, but a named function called myHandler
. Notice that there is no parentheses after function name when we register route because we do not call it at that point.
The function myHandler
accepts one argument with type *macaron.Context
and returns a string. You may notice that we didn’t tell Macaron what arguments should pass to myHandler
when we register routes, and if you look at the m.Get
method, you will see Macaron sees all handlers(macaron.Handler
) as type interface{}
. So how does Macaron know?
This is related to the concept of Service Injection, *macaron.Context
is one of the default injected services, so you can use it directly. Don’t worry about how to inject your own services, it’s just not the time to tell you yet.
Like the previous example, we need to make server listen on a address. This time, we use function from Go standard library called http.ListenAndServe
, which shows any Macaron Instance is fully compatible with Go standard library.
Go Further
You now know about how to write simple code based on Macaron, please try to modify two examples above and make sure you fully understand the words you read.
When you feel comfortable, get up and keep reading on following chapters.
Last updated