This commit is contained in:
lingling 2023-04-20 23:43:26 +08:00
parent 87c52f79a4
commit 02b57be779
1 changed files with 31 additions and 43 deletions

74
main.go
View File

@ -1,67 +1,55 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"time"
"github.com/idoubi/goz"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v4/middleware"
"golang.org/x/net/websocket"
) )
type server struct {
// 通过json标签指定json字段名
Url string `json:"url"`
}
type result struct { type result struct {
// 通过json标签指定json字段名 // 通过json标签指定json字段名
Sataus int `json:"sataus"` Sataus int `json:"sataus"`
Code int `json:"code"` Code int `json:"code"`
Time int `json:"time"` Tip_number int `json:"tip_number"`
} }
var tip_number int = 0
func main() { func main() {
e := echo.New() 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.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.GET("/add", add)
e.GET("/ws", ws)
e.Logger.Fatal(e.Start(":1323")) e.Logger.Fatal(e.Start(":1323"))
} }
func textserver(c echo.Context) error { func add(c echo.Context) error {
tip_number++
// 初始化接收json参数的对象 return c.JSON(http.StatusOK, "ok")
u := new(server)
// 通过Bind将json参数绑定到struct对象
if err := c.Bind(u); err != nil {
return err
}
// 通过结构体对象就可以访问json参数
json := new(result)
json.Code = http.StatusOK
start := time.Now().UnixMilli()
json.Sataus = text_url(u.Url)
elapsed := time.Now().UnixMilli() - start
json.Time = int(elapsed)
return c.JSON(http.StatusOK, json)
} }
func text_url(url string) int { func ws(c echo.Context) error {
cli := goz.NewClient(goz.Options{
Timeout: 2,
})
resp, err := cli.Get(url) websocket.Handler(func(ws *websocket.Conn) {
if err != nil { defer ws.Close()
if resp.IsTimeout() { for {
return -1 // Write
err := websocket.Message.Send(ws, tip_number)
if err != nil {
c.Logger().Error(err)
}
// Read
msg := ""
err = websocket.Message.Receive(ws, &msg)
if err != nil {
c.Logger().Error(err)
}
fmt.Printf("%s\n", msg)
} }
} }).ServeHTTP(c.Response(), c.Request())
return resp.GetStatusCode() return nil
}
func setAccessOriginUrl(c echo.Context) {
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
} }