1) Design template.
Bài này mình note lại cách mà mình được học, và làm như nào để apply framework echo vào golang nhé.
Bạn sẽ chuẩn bị cho mình các sườn của project golang như sau:
Giờ bạn tạo các folder và file như ảnh?
Giờ anh/em copy paste vào file main như dưới nhé
package main
import (
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.Logger.Fatal(e.Start(":1323"))
}
Sau đó bạn mở terminal rồi cd đến chỗ folder chưa file main
rồi gõ như ảnh.
Giờ tạo 1 file handler để response đơn giản:
package handler
import (
"github.com/labstack/echo/v4"
"net/http"
)
func Welcome(c echo.Context) error {
return c.String(http.StatusOK, "Chào mừng bạn đã đến Auto Săn Sale được viết bởi Nim")
}
Tiếp theo tạo file api:
package router
import (
"github.com/labstack/echo/v4"
"hunting-voucher/handler"
)
type API struct {
Echo *echo.Echo
}
func (api *API) SetupRouter() {
api.Echo.GET("/", handler.Welcome)
}
Giờ quay lại sửa file main một chút:
package main
import (
"github.com/labstack/echo/v4"
"hunting-voucher/router"
)
func main() {
e := echo.New()
api := router.API{
Echo: e,
}
api.SetupRouter()
e.Logger.Fatal(e.Start(":1323"))
}
GIờ chúng start lên mà mở browser lên truy cập ngay
2) Apply an http.Handler
to Echo Framework
In this change, we are using the echo.WrapHandler()
function to convert the PromHandler
(an http.Handler
) to an Echo-compatible handler function. This way, the custom Prometheus handler with the registry reg
is utilized when serving the /metrics
endpoint.
package router import ( "github.com/labstack/echo/v4" "metrics-server-exporter/handler" "net/http" ) type API struct { Echo *echo.Echo PromHandler http.Handler } func (api *API) SetupRouter() { api.Echo.GET("/", handler.Welcome) api.Echo.GET("/metrics", echo.WrapHandler(api.PromHandler)) }
Hoặc chúng ta có thể học thêm video này: