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
import (
"fmt"
"net/http"
"time"
"github.com/idoubi/goz"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/net/websocket"
)
type server struct {
// 通过json标签指定json字段名
Url string `json:"url"`
}
type result struct {
// 通过json标签指定json字段名
Sataus int `json:"sataus"`
Code int `json:"code"`
Time int `json:"time"`
Sataus int `json:"sataus"`
Code int `json:"code"`
Tip_number int `json:"tip_number"`
}
var tip_number int = 0
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.GET("/add", add)
e.GET("/ws", ws)
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
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 add(c echo.Context) error {
tip_number++
return c.JSON(http.StatusOK, "ok")
}
func text_url(url string) int {
cli := goz.NewClient(goz.Options{
Timeout: 2,
})
func ws(c echo.Context) error {
resp, err := cli.Get(url)
if err != nil {
if resp.IsTimeout() {
return -1
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
for {
// 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)
}
}
return resp.GetStatusCode()
}
func setAccessOriginUrl(c echo.Context) {
c.Response().Header().Set("Access-Control-Allow-Origin", "*")
}).ServeHTTP(c.Response(), c.Request())
return nil
}