Getting Started with Golang and Echo Framework

Tutorial series for building step by step a real life server in Golang using Echo package.



This is another golang tutorial for echo web framework. ECHO Framework is providing many middleware that supports logger, recover,JWT and basichAuth. You can call Middleware with routes or groups.
. . .

Installation

To get started, we need to create a new Go application: Make the path appropriate for your workspace & install deps.
mkdir go-jwtgo get github.com/labstack/echo
go get github.com/dgrijalva/jwt-go
I will be using the Echo Framework. It’s a very minimalist framework which has the essentials baked in. Let’s create the main.go file by taking the code from the Echo Guide. This will be our starting point.

Hello, World!

Create server.go
package main import ( "net/http" "github.com/labstack/echo" ) func main() { e := echo.New() e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") }) e.Logger.Fatal(e.Start(":1323")) }

Start server
$ go run server.go

Browse to http://localhost:1323 and you should see Hello, World! on the page.

Routing

e.POST("/users", saveUser) e.GET("/users/:id", getUser) e.PUT("/users/:id", updateUser) e.DELETE("/users/:id", deleteUser)

Path Parameters

// e.GET("/users/:id", getUser) func getUser(c echo.Context) error { // User ID from path `users/:id` id := c.Param("id") return c.String(http.StatusOK, id) }

Browse to http://localhost:1323/users/Joe and you should see 'Joe' on the page.

Query Parameters

/show?team=x-men&member=wolverine
//e.GET("/show", show) func show(c echo.Context) error { // Get team and member from the query string team := c.QueryParam("team") member := c.QueryParam("member") return c.String(http.StatusOK, "team:" + team + ", member:" + member) }

Browse to http://localhost:1323/show?team=x-men&member=wolverine and you should see 'team:x-men, member:wolverine' on the page.

Form application/x-www-form-urlencoded

POST /save
// e.POST("/save", save) func save(c echo.Context) error { // Get name and email name := c.FormValue("name") email := c.FormValue("email") return c.String(http.StatusOK, "name:" + name + ", email:" + email) }

Run the following command:
$ curl -F "name=Joe Smith" -F "email=joe@labstack.com" http://localhost:1323/save // => name:Joe Smith, email:joe@labstack.com

Form multipart/form-data

Post /Save
func save(c echo.Context) error { // Get name name := c.FormValue("name") // Get avatar avatar, err := c.FormFile("avatar") if err != nil { return err } // Source src, err := avatar.Open() if err != nil { return err } defer src.Close() // Destination dst, err := os.Create(avatar.Filename) if err != nil { return err } defer dst.Close() // Copy if _, err = io.Copy(dst, src); err != nil { return err } return c.HTML(http.StatusOK, "<b>Thank you! " + name + "</b>") }

Run the following command.
$ curl -F "name=Joe Smith" -F "avatar=@/path/to/your/avatar.png" http://localhost:1323/save // => <b>Thank you! Joe Smith</b>

For checking uploaded image, run the following command.
cd <project directory>
ls avatar.png // => avatar.png

Handling Request

  • Bind json, xml, form or query payload into Go struct based on Content-Type request header.
  • Render response as json or xml with status code.
type User struct { Name string `json:"name" xml:"name" form:"name" query:"name"` Email string `json:"email" xml:"email" form:"email" query:"email"` } e.POST("/users", func(c echo.Context) error { u := new(User) if err := c.Bind(u); err != nil { return err } return c.JSON(http.StatusCreated, u) // or // return c.XML(http.StatusCreated, u) })


Static Content

Serve any file from static directory for path /static/*.
e.Static("/static", "static")

Middleware

Middleware is a function chained in the HTTP request-response cycle with access to Echo#Context which it uses to perform a specific action, for example, logging every request or limiting the number of requests.
Checkout this post for sertting up JWT authentication Middleware in Golang with Echo. https://ednsquare.com/story/jwt-authentication-in-golang-with-echo------T2hTPm

Never miss a post from Chris Gregori, when you sign up for Ednsquare.