MyDocs

# echoを触ってみる

最小構成。

$ go get github.com/labstack/echo/v4
package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello World!")
	})
	e.Logger.Fatal(e.Start(":8080"))
}

path parameters

http://localhost:8080/users/1

1 が返ってくる。

package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/users/:id", getUser)
	e.Logger.Fatal(e.Start(":8080"))
}

func getUser(c echo.Context) error {
	id := c.Param("id")
	return c.String(http.StatusOK, id)
}

query parameters

http://localhost:8080/show?team=x-men&member=wolverine

team: x-men, member: wolverine が返ってくる。

package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/show", show)
	e.Logger.Fatal(e.Start(":8080"))
}

func show(c echo.Context) error {
	team := c.QueryParam("team")
	member := c.QueryParam("member")
	return c.String(http.StatusOK, "team: "+team+", member: "+member)
}

json を返す

http://localhost:8080/json

json を返す。

{
  "name": "Jon",
  "email": "json@sample.com"
}
package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/json", json)
	e.Logger.Fatal(e.Start(":8080"))
}

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func json(c echo.Context) error {
	user := &User{
		Name:  "Jon",
		Email: "json@sample.com",
	}
	return c.JSON(http.StatusOK, user)
}

context.JSON は内部では json.Marshal を使っている。 大きな JSON では非効率なので、その場合は直接 JSON をストリームできる。

package main

import (
	"encoding/json"
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.GET("/jsonStream", jsonStream)
	e.Logger.Fatal(e.Start(":8080"))
}

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func jsonStream(c echo.Context) error {
	user := &User{
		Name:  "Jon",
		Email: "json@sample.com",
	}
	c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
	c.Response().WriteHeader(http.StatusOK)
	return json.NewEncoder(c.Response()).Encode(user)
}

Bind

Context.Bind を使って、ソースからデータ構造にバインドさせる。

$ curl -X POST http://localhost:8080/users \
       -H 'Content-Type: application/json' \
       -d '{"name":"Jon","email":"json@sample.com"}'
{
  "name":"Jon",
  "email":"json@sample.com"
}
package main

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.POST("/users", create)
	e.Logger.Fatal(e.Start(":8080"))
}

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func create(c echo.Context) error {
	user := new(User)
	if err := c.Bind(user); err != nil {
		return err
	}
	fmt.Println(user)

	bindUser := &User{
		Name:  user.Name,
		Email: user.Email,
	}

	return c.JSON(http.StatusOK, bindUser)
}