alist/internal/message/http.go

83 lines
1.6 KiB
Go
Raw Normal View History

2022-07-01 08:53:01 +00:00
package message
import (
2022-08-03 06:26:59 +00:00
"time"
2022-07-01 08:53:01 +00:00
"github.com/alist-org/alist/v3/server/common"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
2022-08-13 19:05:30 +00:00
type Http struct {
Received chan string // received messages from web
ToSend chan Message // messages to send to web
2022-07-01 08:53:01 +00:00
}
type Req struct {
Message string `json:"message" form:"message"`
}
2022-08-13 19:05:30 +00:00
func (p *Http) GetHandle(c *gin.Context) {
2022-07-01 08:53:01 +00:00
select {
case message := <-p.ToSend:
common.SuccessResp(c, message)
default:
common.ErrorStrResp(c, "no message", 404)
}
}
2022-08-13 19:05:30 +00:00
func (p *Http) SendHandle(c *gin.Context) {
2022-07-01 08:53:01 +00:00
var req Req
if err := c.ShouldBind(&req); err != nil {
common.ErrorResp(c, err, 400)
return
}
select {
case p.Received <- req.Message:
common.SuccessResp(c)
default:
2022-08-13 19:05:30 +00:00
common.ErrorStrResp(c, "nowhere needed", 500)
2022-07-01 08:53:01 +00:00
}
}
2022-08-13 19:05:30 +00:00
func (p *Http) Send(message Message) error {
2022-07-01 08:53:01 +00:00
select {
2022-08-13 19:05:30 +00:00
case p.ToSend <- message:
2022-07-01 08:53:01 +00:00
return nil
default:
return errors.New("send failed")
}
}
2022-08-13 19:05:30 +00:00
func (p *Http) Receive() (string, error) {
2022-07-01 08:53:01 +00:00
select {
case message := <-p.Received:
return message, nil
default:
return "", errors.New("receive failed")
}
}
2022-08-13 19:05:30 +00:00
func (p *Http) WaitSend(message Message, d int) error {
2022-07-01 08:53:01 +00:00
select {
2022-08-13 19:05:30 +00:00
case p.ToSend <- message:
2022-07-01 08:53:01 +00:00
return nil
case <-time.After(time.Duration(d) * time.Second):
return errors.New("send timeout")
}
}
2022-08-13 19:05:30 +00:00
func (p *Http) WaitReceive(d int) (string, error) {
2022-07-01 08:53:01 +00:00
select {
case message := <-p.Received:
return message, nil
case <-time.After(time.Duration(d) * time.Second):
return "", errors.New("receive timeout")
}
}
2022-08-13 19:05:30 +00:00
var HttpInstance = &Http{
2022-07-01 08:53:01 +00:00
Received: make(chan string),
2022-08-13 19:05:30 +00:00
ToSend: make(chan Message),
2022-07-01 08:53:01 +00:00
}