dashboard/services/uniss/httphandle.go

67 lines
1.1 KiB
Go

package uniss
import (
"dashboard/models"
"sync"
)
type httpHandle struct {
httpC chan *models.UnisHttpRequest
mu sync.RWMutex
mapFn map[string]HttpHandler
}
type HttpHandler func(*models.UnisHttpRequest) (*models.UnisHttpResponse, error)
func newhttpHandle() *httpHandle {
res := new(httpHandle)
res.httpC = make(chan *models.UnisHttpRequest)
res.mapFn = make(map[string]HttpHandler)
return res
}
func (u *httpHandle) httpHandle(msg *models.UnisHttpRequest) {
var res *models.UnisHttpResponse
resC := msg.ResC
defer func() {
if resC != nil {
resC <- res
}
}()
fn, ok := u.getHandle(msg.Id)
if ok {
if re, err := fn(msg); err == nil {
res = re
}
}
}
func (u *httpHandle) pushHandle(key string, handle HttpHandler) {
u.mu.Lock()
defer u.mu.Unlock()
u.mapFn[key] = handle
}
func (u *httpHandle) delHandle(key string) {
u.mu.Lock()
defer u.mu.Unlock()
delete(u.mapFn, key)
}
func (u *httpHandle) getHandle(key string) (HttpHandler, bool) {
u.mu.RLock()
defer u.mu.RUnlock()
res, ok := u.mapFn[key]
if !ok {
return nil, false
}
return res, ok
}