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

64
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参数 func ws(c echo.Context) error {
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 {
cli := goz.NewClient(goz.Options{
Timeout: 2,
})
resp, err := cli.Get(url) websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
for {
// Write
err := websocket.Message.Send(ws, tip_number)
if err != nil { if err != nil {
if resp.IsTimeout() { c.Logger().Error(err)
return -1
} }
// Read
msg := ""
err = websocket.Message.Receive(ws, &msg)
if err != nil {
c.Logger().Error(err)
} }
return resp.GetStatusCode() fmt.Printf("%s\n", msg)
} }
func setAccessOriginUrl(c echo.Context) { }).ServeHTTP(c.Response(), c.Request())
c.Response().Header().Set("Access-Control-Allow-Origin", "*") return nil
} }