# echo를 이용한 RestfulAPI 구현
# echo
echo (opens new window)는 Go의 웹 프레임 워크다. 공식 홈페이지에서는 아래와 같이 소개하고 있으며 이를 통해 REST API 예제를 구현해보자.
echo
High performance, extensible, minimalist Go web framework
# 프로젝트 생성
go mod init
go get -u github.com/labstack/echo/...
아래는 간단한 hello world 출력하는 예제다.
main.go
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
//에코 인스턴스 생성
e := echo.New()
//미들웨어 선언
e.Use(middleware.Logger()) //http 요청 기록
e.Use(middleware.Recover()) //패닉 복구
//라우팅
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello World!")
})
// http://localhost:8081/
e.Logger.Fatal(e.Start(":8081"))
}
아래처럼 따로 함수로 빼서 써도 된다.
func hellowrold(c echo.Context) error {
return c.String(http.StatusOK, "Hello World!")
}
e.GET("/", hellowrold)
# Get
# Parameter
func getUser(c echo.Context) error {
id := c.Param("id")
return c.String(http.StatusOK, id)
}
e.GET("/users/:id", getUser)
localhost:8081/users/123
로 접속하면 123이 출력되는걸 확인할수있다.
# QueryParameters
func listUser(c echo.Context) error {
page := c.QueryParam("page")
return c.String(http.StatusOK, "page: "+page)
}
e.GET("/users", listUser)
localhost:8081/users?page=2
로 접속하면 2가 출력되는걸 확인할수있다.
# POST
func login(c echo.Context) error {
id := c.FormValue("id")
pw := c.FormValue("pw")
return c.String(http.StatusOK, "id:"+id+", pw:"+pw)
}
e.POST("/login", login)
POST 요청이기 때문에 PostMan으로 확인할수있다.
id:admin, pw:1234