go_echo/main.go

68 lines
1.5 KiB
Go
Raw Normal View History

2023-03-20 18:19:02 +08:00
package main
import (
"net/http"
2023-04-01 14:51:08 +08:00
"time"
2023-03-20 18:19:02 +08:00
"github.com/idoubi/goz"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type server struct {
// 通过json标签指定json字段名
Url string `json:"url"`
}
type result struct {
// 通过json标签指定json字段名
2023-04-01 15:01:06 +08:00
Sataus int `json:"sataus"`
Code int `json:"code"`
Time int `json:"time"`
2023-03-20 18:19:02 +08:00
}
func main() {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{AllowOrigins: []string{"*"}, AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE}}))
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.POST("/textserver", textserver)
e.Logger.Fatal(e.Start(":1323"))
}
func textserver(c echo.Context) error {
// 初始化接收json参数的对象
u := new(server)
// 通过Bind将json参数绑定到struct对象
if err := c.Bind(u); err != nil {
return err
}
// 通过结构体对象就可以访问json参数
json := new(result)
json.Code = http.StatusOK
2023-04-01 15:01:06 +08:00
start := time.Now().UnixMilli()
2023-03-20 18:19:02 +08:00
json.Sataus = text_url(u.Url)
2023-04-01 15:01:06 +08:00
elapsed := time.Now().UnixMilli() - start
json.Time = int(elapsed)
2023-03-20 18:19:02 +08:00
return c.JSON(http.StatusOK, json)
}
func text_url(url string) int {
cli := goz.NewClient(goz.Options{
2023-03-31 16:40:19 +08:00
Timeout: 2,
2023-03-20 18:19:02 +08:00
})
resp, err := cli.Get(url)
if err != nil {
if resp.IsTimeout() {
return -1
}
}
return resp.GetStatusCode()
}
func setAccessOriginUrl(c echo.Context) {
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
}