go_echo/main.go

63 lines
1.4 KiB
Go

package main
import (
"net/http"
"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字段名
Sataus int `json:"sataus"`
Code int `json:"code"`
}
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
json.Sataus = text_url(u.Url)
return c.JSON(http.StatusOK, json)
}
func text_url(url string) int {
cli := goz.NewClient(goz.Options{
Timeout: 2,
})
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", "*")
}