go_echo/main.go

100 lines
2.2 KiB
Go

/*
* @Author: giaogiao giaogiao
* @Date: 2023-08-07 09:56:42
* @LastEditors: giaogiao giaogiao
* @LastEditTime: 2023-08-07 11:54:17
* @FilePath: \go_echo\main.go
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
package main
import (
"net/http"
"sync"
"time"
"github.com/idoubi/goz"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type TheServerReturns struct {
Code int `json:"code"`
Message string `json:"message"`
Data Data `json:"data"`
}
type Items struct {
Code int `json:"code"`
Time int `json:"time"`
URL string `json:"url"`
}
type Data struct {
Items []Items `json:"items"`
}
type ServerAccept struct {
Urls []Urls `json:"urls"`
}
type Urls struct {
URL string `json:"url"`
}
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(ServerAccept)
// 通过Bind将json参数绑定到struct对象
if err := c.Bind(u); err != nil {
return err
}
// 通过结构体对象就可以访问json参数
json := new(TheServerReturns)
json.Code = http.StatusOK
var wg sync.WaitGroup
wg.Add(len(u.Urls))
for _, url := range u.Urls {
item := new(Items)
go text_url2(json, url.URL, item, wg.Done)
}
wg.Wait()
return c.JSON(http.StatusOK, json)
}
func text_url2(json *TheServerReturns, url string, item *Items, done func()) int {
defer done()
// item := new(Items)
item.URL = url
start := time.Now().UnixMilli()
cli := goz.NewClient(goz.Options{
Timeout: 2,
})
resp, err := cli.Get(url)
if err != nil {
if resp.IsTimeout() {
item.Code = -1
item.Time = -1
return 0
}
}
elapsed := time.Now().UnixMilli() - start
item.Code = resp.GetStatusCode()
item.Time = int(elapsed)
json.Data.Items = append(json.Data.Items, *item)
return 0
}