diff --git a/app/http/controllers/cert_controller.go b/app/http/controllers/cert_controller.go index 4beffd6f..f148ba5e 100644 --- a/app/http/controllers/cert_controller.go +++ b/app/http/controllers/cert_controller.go @@ -10,6 +10,7 @@ import ( "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" "github.com/TheTNB/panel/v2/pkg/acme" + "github.com/TheTNB/panel/v2/pkg/h" ) type CertController struct { @@ -34,7 +35,7 @@ func NewCertController() *CertController { // @Success 200 {object} SuccessResponse // @Router /panel/cert/caProviders [get] func (r *CertController) CAProviders(ctx http.Context) http.Response { - return Success(ctx, []map[string]string{ + return h.Success(ctx, []map[string]string{ { "name": "Let's Encrypt", "ca": "letsencrypt", @@ -68,7 +69,7 @@ func (r *CertController) CAProviders(ctx http.Context) http.Response { // @Success 200 {object} SuccessResponse // @Router /panel/cert/dnsProviders [get] func (r *CertController) DNSProviders(ctx http.Context) http.Response { - return Success(ctx, []map[string]any{ + return h.Success(ctx, []map[string]any{ { "name": "DNSPod", "dns": acme.DnsPod, @@ -98,7 +99,7 @@ func (r *CertController) DNSProviders(ctx http.Context) http.Response { // @Success 200 {object} SuccessResponse // @Router /panel/cert/algorithms [get] func (r *CertController) Algorithms(ctx http.Context) http.Response { - return Success(ctx, []map[string]any{ + return h.Success(ctx, []map[string]any{ { "name": "EC256", "key": acme.KeyEC256, @@ -130,7 +131,7 @@ func (r *CertController) Algorithms(ctx http.Context) http.Response { // @Router /panel/cert/users [get] func (r *CertController) UserList(ctx http.Context) http.Response { var paginateRequest commonrequests.Paginate - sanitize := SanitizeRequest(ctx, &paginateRequest) + sanitize := h.SanitizeRequest(ctx, &paginateRequest) if sanitize != nil { return sanitize } @@ -142,10 +143,10 @@ func (r *CertController) UserList(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("获取ACME用户列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": users, }) @@ -164,7 +165,7 @@ func (r *CertController) UserList(ctx http.Context) http.Response { // @Router /panel/cert/users [post] func (r *CertController) UserStore(ctx http.Context) http.Response { var storeRequest requests.UserStore - sanitize := SanitizeRequest(ctx, &storeRequest) + sanitize := h.SanitizeRequest(ctx, &storeRequest) if sanitize != nil { return sanitize } @@ -174,10 +175,10 @@ func (r *CertController) UserStore(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("添加ACME用户失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // UserUpdate @@ -194,7 +195,7 @@ func (r *CertController) UserStore(ctx http.Context) http.Response { // @Router /panel/cert/users/{id} [put] func (r *CertController) UserUpdate(ctx http.Context) http.Response { var updateRequest requests.UserUpdate - sanitize := SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } @@ -205,10 +206,10 @@ func (r *CertController) UserUpdate(ctx http.Context) http.Response { "userID": updateRequest.ID, "error": err.Error(), }).Info("更新ACME用户失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // UserShow @@ -223,7 +224,7 @@ func (r *CertController) UserUpdate(ctx http.Context) http.Response { // @Router /panel/cert/users/{id} [get] func (r *CertController) UserShow(ctx http.Context) http.Response { var showAndDestroyRequest requests.UserShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -234,10 +235,10 @@ func (r *CertController) UserShow(ctx http.Context) http.Response { "userID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("获取ACME用户失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, user) + return h.Success(ctx, user) } // UserDestroy @@ -253,7 +254,7 @@ func (r *CertController) UserShow(ctx http.Context) http.Response { // @Router /panel/cert/users/{id} [delete] func (r *CertController) UserDestroy(ctx http.Context) http.Response { var showAndDestroyRequest requests.UserShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -264,10 +265,10 @@ func (r *CertController) UserDestroy(ctx http.Context) http.Response { "userID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("删除ACME用户失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // DNSList @@ -282,7 +283,7 @@ func (r *CertController) UserDestroy(ctx http.Context) http.Response { // @Router /panel/cert/dns [get] func (r *CertController) DNSList(ctx http.Context) http.Response { var paginateRequest commonrequests.Paginate - sanitize := SanitizeRequest(ctx, &paginateRequest) + sanitize := h.SanitizeRequest(ctx, &paginateRequest) if sanitize != nil { return sanitize } @@ -294,10 +295,10 @@ func (r *CertController) DNSList(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("获取DNS接口列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": dns, }) @@ -316,7 +317,7 @@ func (r *CertController) DNSList(ctx http.Context) http.Response { // @Router /panel/cert/dns [post] func (r *CertController) DNSStore(ctx http.Context) http.Response { var storeRequest requests.DNSStore - sanitize := SanitizeRequest(ctx, &storeRequest) + sanitize := h.SanitizeRequest(ctx, &storeRequest) if sanitize != nil { return sanitize } @@ -326,10 +327,10 @@ func (r *CertController) DNSStore(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("添加DNS接口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // DNSShow @@ -344,7 +345,7 @@ func (r *CertController) DNSStore(ctx http.Context) http.Response { // @Router /panel/cert/dns/{id} [get] func (r *CertController) DNSShow(ctx http.Context) http.Response { var showAndDestroyRequest requests.DNSShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -355,10 +356,10 @@ func (r *CertController) DNSShow(ctx http.Context) http.Response { "dnsID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("获取DNS接口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, dns) + return h.Success(ctx, dns) } // DNSUpdate @@ -375,7 +376,7 @@ func (r *CertController) DNSShow(ctx http.Context) http.Response { // @Router /panel/cert/dns/{id} [put] func (r *CertController) DNSUpdate(ctx http.Context) http.Response { var updateRequest requests.DNSUpdate - sanitize := SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } @@ -386,10 +387,10 @@ func (r *CertController) DNSUpdate(ctx http.Context) http.Response { "dnsID": updateRequest.ID, "error": err.Error(), }).Info("更新DNS接口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // DNSDestroy @@ -405,7 +406,7 @@ func (r *CertController) DNSUpdate(ctx http.Context) http.Response { // @Router /panel/cert/dns/{id} [delete] func (r *CertController) DNSDestroy(ctx http.Context) http.Response { var showAndDestroyRequest requests.DNSShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -416,10 +417,10 @@ func (r *CertController) DNSDestroy(ctx http.Context) http.Response { "dnsID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("删除DNS接口失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // CertList @@ -434,7 +435,7 @@ func (r *CertController) DNSDestroy(ctx http.Context) http.Response { // @Router /panel/cert/certs [get] func (r *CertController) CertList(ctx http.Context) http.Response { var paginateRequest commonrequests.Paginate - sanitize := SanitizeRequest(ctx, &paginateRequest) + sanitize := h.SanitizeRequest(ctx, &paginateRequest) if sanitize != nil { return sanitize } @@ -446,10 +447,10 @@ func (r *CertController) CertList(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("获取证书列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": certs, }) @@ -468,7 +469,7 @@ func (r *CertController) CertList(ctx http.Context) http.Response { // @Router /panel/cert/certs [post] func (r *CertController) CertStore(ctx http.Context) http.Response { var storeRequest requests.CertStore - sanitize := SanitizeRequest(ctx, &storeRequest) + sanitize := h.SanitizeRequest(ctx, &storeRequest) if sanitize != nil { return sanitize } @@ -478,10 +479,10 @@ func (r *CertController) CertStore(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("添加证书失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // CertUpdate @@ -498,7 +499,7 @@ func (r *CertController) CertStore(ctx http.Context) http.Response { // @Router /panel/cert/certs/{id} [put] func (r *CertController) CertUpdate(ctx http.Context) http.Response { var updateRequest requests.CertUpdate - sanitize := SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } @@ -509,10 +510,10 @@ func (r *CertController) CertUpdate(ctx http.Context) http.Response { "certID": updateRequest.ID, "error": err.Error(), }).Info("更新证书失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // CertShow @@ -527,7 +528,7 @@ func (r *CertController) CertUpdate(ctx http.Context) http.Response { // @Router /panel/cert/certs/{id} [get] func (r *CertController) CertShow(ctx http.Context) http.Response { var showAndDestroyRequest requests.CertShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -538,10 +539,10 @@ func (r *CertController) CertShow(ctx http.Context) http.Response { "certID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("获取证书失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, cert) + return h.Success(ctx, cert) } // CertDestroy @@ -557,7 +558,7 @@ func (r *CertController) CertShow(ctx http.Context) http.Response { // @Router /panel/cert/certs/{id} [delete] func (r *CertController) CertDestroy(ctx http.Context) http.Response { var showAndDestroyRequest requests.CertShowAndDestroy - sanitize := SanitizeRequest(ctx, &showAndDestroyRequest) + sanitize := h.SanitizeRequest(ctx, &showAndDestroyRequest) if sanitize != nil { return sanitize } @@ -568,10 +569,10 @@ func (r *CertController) CertDestroy(ctx http.Context) http.Response { "certID": showAndDestroyRequest.ID, "error": err.Error(), }).Info("删除证书失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Obtain @@ -587,7 +588,7 @@ func (r *CertController) CertDestroy(ctx http.Context) http.Response { // @Router /panel/cert/obtain [post] func (r *CertController) Obtain(ctx http.Context) http.Response { var obtainRequest requests.Obtain - sanitize := SanitizeRequest(ctx, &obtainRequest) + sanitize := h.SanitizeRequest(ctx, &obtainRequest) if sanitize != nil { return sanitize } @@ -598,7 +599,7 @@ func (r *CertController) Obtain(ctx http.Context) http.Response { "certID": obtainRequest.ID, "error": err.Error(), }).Info("获取证书失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if cert.DNS != nil || cert.Website != nil { @@ -610,10 +611,10 @@ func (r *CertController) Obtain(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("签发证书失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Renew @@ -629,7 +630,7 @@ func (r *CertController) Obtain(ctx http.Context) http.Response { // @Router /panel/cert/renew [post] func (r *CertController) Renew(ctx http.Context) http.Response { var renewRequest requests.Renew - sanitize := SanitizeRequest(ctx, &renewRequest) + sanitize := h.SanitizeRequest(ctx, &renewRequest) if sanitize != nil { return sanitize } @@ -639,10 +640,10 @@ func (r *CertController) Renew(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("续签证书失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ManualDNS @@ -658,7 +659,7 @@ func (r *CertController) Renew(ctx http.Context) http.Response { // @Router /panel/cert/manualDNS [post] func (r *CertController) ManualDNS(ctx http.Context) http.Response { var obtainRequest requests.Obtain - sanitize := SanitizeRequest(ctx, &obtainRequest) + sanitize := h.SanitizeRequest(ctx, &obtainRequest) if sanitize != nil { return sanitize } @@ -668,10 +669,10 @@ func (r *CertController) ManualDNS(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "证书管理").With(map[string]any{ "error": err.Error(), }).Info("获取手动DNS记录失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, resolves) + return h.Success(ctx, resolves) } // Deploy @@ -687,7 +688,7 @@ func (r *CertController) ManualDNS(ctx http.Context) http.Response { // @Router /panel/cert/deploy [post] func (r *CertController) Deploy(ctx http.Context) http.Response { var deployRequest requests.CertDeploy - sanitize := SanitizeRequest(ctx, &deployRequest) + sanitize := h.SanitizeRequest(ctx, &deployRequest) if sanitize != nil { return sanitize } @@ -698,8 +699,8 @@ func (r *CertController) Deploy(ctx http.Context) http.Response { "certID": deployRequest.ID, "error": err.Error(), }).Info("部署证书失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/container_controller.go b/app/http/controllers/container_controller.go index 6e48c4a1..be82d3ba 100644 --- a/app/http/controllers/container_controller.go +++ b/app/http/controllers/container_controller.go @@ -13,6 +13,7 @@ import ( requests "github.com/TheTNB/panel/v2/app/http/requests/container" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/str" ) @@ -39,10 +40,10 @@ func NewContainerController() *ContainerController { func (r *ContainerController) ContainerList(ctx http.Context) http.Response { containers, err := r.container.ContainerListAll() if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := Paginate(ctx, containers) + paged, total := h.Paginate(ctx, containers) items := make([]any, 0) for _, item := range paged { @@ -64,7 +65,7 @@ func (r *ContainerController) ContainerList(ctx http.Context) http.Response { }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": items, }) @@ -84,10 +85,10 @@ func (r *ContainerController) ContainerSearch(ctx http.Context) http.Response { fields := strings.Fields(ctx.Request().Query("name")) containers, err := r.container.ContainerListByNames(fields) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, containers) + return h.Success(ctx, containers) } // ContainerCreate @@ -103,7 +104,7 @@ func (r *ContainerController) ContainerSearch(ctx http.Context) http.Response { // @Router /panel/container/create [post] func (r *ContainerController) ContainerCreate(ctx http.Context) http.Response { var request requests.ContainerCreate - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } @@ -113,10 +114,10 @@ func (r *ContainerController) ContainerCreate(ctx http.Context) http.Response { portMap := make(nat.PortMap) for _, port := range request.Ports { if port.ContainerStart-port.ContainerEnd != port.HostStart-port.HostEnd { - return Error(ctx, http.StatusUnprocessableEntity, fmt.Sprintf("容器端口和主机端口数量不匹配(容器: %d 主机: %d)", port.ContainerStart-port.ContainerEnd, port.HostStart-port.HostEnd)) + return h.Error(ctx, http.StatusUnprocessableEntity, fmt.Sprintf("容器端口和主机端口数量不匹配(容器: %d 主机: %d)", port.ContainerStart-port.ContainerEnd, port.HostStart-port.HostEnd)) } if port.ContainerStart > port.ContainerEnd || port.HostStart > port.HostEnd || port.ContainerStart < 1 || port.HostStart < 1 { - return Error(ctx, http.StatusUnprocessableEntity, "端口范围不正确") + return h.Error(ctx, http.StatusUnprocessableEntity, "端口范围不正确") } count := 0 @@ -178,14 +179,14 @@ func (r *ContainerController) ContainerCreate(ctx http.Context) http.Response { networkConf, ) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = r.container.ContainerStart(id); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, id) + return h.Success(ctx, id) } // ContainerRemove @@ -200,15 +201,15 @@ func (r *ContainerController) ContainerCreate(ctx http.Context) http.Response { // @Router /panel/container/remove [post] func (r *ContainerController) ContainerRemove(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerRemove(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerStart @@ -223,15 +224,15 @@ func (r *ContainerController) ContainerRemove(ctx http.Context) http.Response { // @Router /panel/container/start [post] func (r *ContainerController) ContainerStart(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerStart(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerStop @@ -246,15 +247,15 @@ func (r *ContainerController) ContainerStart(ctx http.Context) http.Response { // @Router /panel/container/stop [post] func (r *ContainerController) ContainerStop(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerStop(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerRestart @@ -269,15 +270,15 @@ func (r *ContainerController) ContainerStop(ctx http.Context) http.Response { // @Router /panel/container/restart [post] func (r *ContainerController) ContainerRestart(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerRestart(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerPause @@ -291,15 +292,15 @@ func (r *ContainerController) ContainerRestart(ctx http.Context) http.Response { // @Success 200 {object} SuccessResponse func (r *ContainerController) ContainerPause(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerPause(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerUnpause @@ -315,15 +316,15 @@ func (r *ContainerController) ContainerPause(ctx http.Context) http.Response { // @Router /panel/container/unpause [post] func (r *ContainerController) ContainerUnpause(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerUnpause(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerInspect @@ -338,16 +339,16 @@ func (r *ContainerController) ContainerUnpause(ctx http.Context) http.Response { // @Router /panel/container/inspect [get] func (r *ContainerController) ContainerInspect(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.ContainerInspect(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // ContainerKill @@ -362,15 +363,15 @@ func (r *ContainerController) ContainerInspect(ctx http.Context) http.Response { // @Router /panel/container/kill [post] func (r *ContainerController) ContainerKill(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerKill(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerRename @@ -385,15 +386,15 @@ func (r *ContainerController) ContainerKill(ctx http.Context) http.Response { // @Router /panel/container/rename [post] func (r *ContainerController) ContainerRename(ctx http.Context) http.Response { var request requests.ContainerRename - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ContainerRename(request.ID, request.Name); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ContainerStats @@ -408,16 +409,16 @@ func (r *ContainerController) ContainerRename(ctx http.Context) http.Response { // @Router /panel/container/stats [get] func (r *ContainerController) ContainerStats(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.ContainerStats(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // ContainerExist @@ -432,16 +433,16 @@ func (r *ContainerController) ContainerStats(ctx http.Context) http.Response { // @Router /panel/container/exist [get] func (r *ContainerController) ContainerExist(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } exist, err := r.container.ContainerExist(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, exist) + return h.Success(ctx, exist) } // ContainerLogs @@ -456,16 +457,16 @@ func (r *ContainerController) ContainerExist(ctx http.Context) http.Response { // @Router /panel/container/logs [get] func (r *ContainerController) ContainerLogs(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.ContainerLogs(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // ContainerPrune @@ -479,10 +480,10 @@ func (r *ContainerController) ContainerLogs(ctx http.Context) http.Response { // @Router /panel/container/prune [post] func (r *ContainerController) ContainerPrune(ctx http.Context) http.Response { if err := r.container.ContainerPrune(); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // NetworkList @@ -498,10 +499,10 @@ func (r *ContainerController) ContainerPrune(ctx http.Context) http.Response { func (r *ContainerController) NetworkList(ctx http.Context) http.Response { networks, err := r.container.NetworkList() if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := Paginate(ctx, networks) + paged, total := h.Paginate(ctx, networks) items := make([]any, 0) for _, item := range paged { @@ -534,7 +535,7 @@ func (r *ContainerController) NetworkList(ctx http.Context) http.Response { }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": items, }) @@ -553,16 +554,16 @@ func (r *ContainerController) NetworkList(ctx http.Context) http.Response { // @Router /panel/container/network/create [post] func (r *ContainerController) NetworkCreate(ctx http.Context) http.Response { var request requests.NetworkCreate - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } id, err := r.container.NetworkCreate(request) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, id) + return h.Success(ctx, id) } // NetworkRemove @@ -577,15 +578,15 @@ func (r *ContainerController) NetworkCreate(ctx http.Context) http.Response { // @Router /panel/container/network/remove [post] func (r *ContainerController) NetworkRemove(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.NetworkRemove(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // NetworkExist @@ -600,16 +601,16 @@ func (r *ContainerController) NetworkRemove(ctx http.Context) http.Response { // @Router /panel/container/network/exist [get] func (r *ContainerController) NetworkExist(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } exist, err := r.container.NetworkExist(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, exist) + return h.Success(ctx, exist) } // NetworkInspect @@ -624,16 +625,16 @@ func (r *ContainerController) NetworkExist(ctx http.Context) http.Response { // @Router /panel/container/network/inspect [get] func (r *ContainerController) NetworkInspect(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.NetworkInspect(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // NetworkConnect @@ -649,15 +650,15 @@ func (r *ContainerController) NetworkInspect(ctx http.Context) http.Response { // @Router /panel/container/network/connect [post] func (r *ContainerController) NetworkConnect(ctx http.Context) http.Response { var request requests.NetworkConnectDisConnect - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.NetworkConnect(request.Network, request.Container); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // NetworkDisconnect @@ -673,15 +674,15 @@ func (r *ContainerController) NetworkConnect(ctx http.Context) http.Response { // @Router /panel/container/network/disconnect [post] func (r *ContainerController) NetworkDisconnect(ctx http.Context) http.Response { var request requests.NetworkConnectDisConnect - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.NetworkDisconnect(request.Network, request.Container); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // NetworkPrune @@ -695,10 +696,10 @@ func (r *ContainerController) NetworkDisconnect(ctx http.Context) http.Response // @Router /panel/container/network/prune [post] func (r *ContainerController) NetworkPrune(ctx http.Context) http.Response { if err := r.container.NetworkPrune(); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ImageList @@ -714,10 +715,10 @@ func (r *ContainerController) NetworkPrune(ctx http.Context) http.Response { func (r *ContainerController) ImageList(ctx http.Context) http.Response { images, err := r.container.ImageList() if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := Paginate(ctx, images) + paged, total := h.Paginate(ctx, images) items := make([]any, 0) for _, item := range paged { @@ -732,7 +733,7 @@ func (r *ContainerController) ImageList(ctx http.Context) http.Response { }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": items, }) @@ -750,16 +751,16 @@ func (r *ContainerController) ImageList(ctx http.Context) http.Response { // @Router /panel/container/image/exist [get] func (r *ContainerController) ImageExist(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } exist, err := r.container.ImageExist(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, exist) + return h.Success(ctx, exist) } // ImagePull @@ -775,15 +776,15 @@ func (r *ContainerController) ImageExist(ctx http.Context) http.Response { // @Router /panel/container/image/pull [post] func (r *ContainerController) ImagePull(ctx http.Context) http.Response { var request requests.ImagePull - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ImagePull(request); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ImageRemove @@ -798,15 +799,15 @@ func (r *ContainerController) ImagePull(ctx http.Context) http.Response { // @Router /panel/container/image/remove [post] func (r *ContainerController) ImageRemove(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.ImageRemove(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ImagePrune @@ -820,10 +821,10 @@ func (r *ContainerController) ImageRemove(ctx http.Context) http.Response { // @Router /panel/container/image/prune [post] func (r *ContainerController) ImagePrune(ctx http.Context) http.Response { if err := r.container.ImagePrune(); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ImageInspect @@ -838,16 +839,16 @@ func (r *ContainerController) ImagePrune(ctx http.Context) http.Response { // @Router /panel/container/image/inspect [get] func (r *ContainerController) ImageInspect(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.ImageInspect(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // VolumeList @@ -863,10 +864,10 @@ func (r *ContainerController) ImageInspect(ctx http.Context) http.Response { func (r *ContainerController) VolumeList(ctx http.Context) http.Response { volumes, err := r.container.VolumeList() if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := Paginate(ctx, volumes) + paged, total := h.Paginate(ctx, volumes) items := make([]any, 0) for _, item := range paged { @@ -890,7 +891,7 @@ func (r *ContainerController) VolumeList(ctx http.Context) http.Response { }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": items, }) @@ -909,16 +910,16 @@ func (r *ContainerController) VolumeList(ctx http.Context) http.Response { // @Router /panel/container/volume/create [post] func (r *ContainerController) VolumeCreate(ctx http.Context) http.Response { var request requests.VolumeCreate - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.VolumeCreate(request) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data.Name) + return h.Success(ctx, data.Name) } // VolumeExist @@ -933,16 +934,16 @@ func (r *ContainerController) VolumeCreate(ctx http.Context) http.Response { // @Router /panel/container/volume/exist [get] func (r *ContainerController) VolumeExist(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } exist, err := r.container.VolumeExist(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, exist) + return h.Success(ctx, exist) } // VolumeInspect @@ -957,16 +958,16 @@ func (r *ContainerController) VolumeExist(ctx http.Context) http.Response { // @Router /panel/container/volume/inspect [get] func (r *ContainerController) VolumeInspect(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } data, err := r.container.VolumeInspect(request.ID) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, data) + return h.Success(ctx, data) } // VolumeRemove @@ -981,15 +982,15 @@ func (r *ContainerController) VolumeInspect(ctx http.Context) http.Response { // @Router /panel/container/volume/remove [post] func (r *ContainerController) VolumeRemove(ctx http.Context) http.Response { var request requests.ID - if sanitize := SanitizeRequest(ctx, &request); sanitize != nil { + if sanitize := h.SanitizeRequest(ctx, &request); sanitize != nil { return sanitize } if err := r.container.VolumeRemove(request.ID); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // VolumePrune @@ -1003,8 +1004,8 @@ func (r *ContainerController) VolumeRemove(ctx http.Context) http.Response { // @Router /panel/container/volume/prune [post] func (r *ContainerController) VolumePrune(ctx http.Context) http.Response { if err := r.container.VolumePrune(); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/cron_controller.go b/app/http/controllers/cron_controller.go index b235b0ce..7b5c76c3 100644 --- a/app/http/controllers/cron_controller.go +++ b/app/http/controllers/cron_controller.go @@ -12,6 +12,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -41,10 +42,10 @@ func (r *CronController) List(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{ "error": err.Error(), }).Info("查询计划任务列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": crons, }) @@ -52,7 +53,7 @@ func (r *CronController) List(ctx http.Context) http.Response { // Add 添加计划任务 func (r *CronController) Add(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required|min_len:1|max_len:255", "time": "required", "script": "required", @@ -64,7 +65,7 @@ func (r *CronController) Add(ctx http.Context) http.Response { // 单独验证时间格式 if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) { - return Error(ctx, http.StatusUnprocessableEntity, "时间格式错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "时间格式错误") } script := ctx.Request().Input("script") @@ -113,17 +114,17 @@ panel cutoff ${name} ${save} 2>&1 shellDir := "/www/server/cron/" shellLogDir := "/www/server/cron/logs/" if !io.Exists(shellDir) { - return Error(ctx, http.StatusInternalServerError, "计划任务目录不存在") + return h.Error(ctx, http.StatusInternalServerError, "计划任务目录不存在") } if !io.Exists(shellLogDir) { - return Error(ctx, http.StatusInternalServerError, "计划任务日志目录不存在") + return h.Error(ctx, http.StatusInternalServerError, "计划任务日志目录不存在") } shellFile := strconv.Itoa(int(carbon.Now().Timestamp())) + str.RandomString(16) if err := io.Write(shellDir+shellFile+".sh", script, 0700); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if out, err := shell.Execf("dos2unix " + shellDir + shellFile + ".sh"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } var cron models.Cron @@ -138,14 +139,14 @@ panel cutoff ${name} ${save} 2>&1 facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{ "error": err.Error(), }).Info("保存计划任务失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := r.cron.AddToSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "id": cron.ID, }) } @@ -155,20 +156,20 @@ func (r *CronController) Script(ctx http.Context) http.Response { var cron models.Cron err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron) if err != nil { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") } script, err := io.Read(cron.Shell) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, script) + return h.Success(ctx, script) } // Update 更新计划任务 func (r *CronController) Update(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required|min_len:1|max_len:255", "time": "required", "script": "required", @@ -178,16 +179,16 @@ func (r *CronController) Update(ctx http.Context) http.Response { // 单独验证时间格式 if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) { - return Error(ctx, http.StatusUnprocessableEntity, "时间格式错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "时间格式错误") } var cron models.Cron if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") } if !cron.Status { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务已禁用") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务已禁用") } cron.Time = ctx.Request().Input("time") @@ -196,55 +197,55 @@ func (r *CronController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{ "error": err.Error(), }).Info("更新计划任务失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := io.Write(cron.Shell, ctx.Request().Input("script"), 0644); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if out, err := shell.Execf("dos2unix " + cron.Shell); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err := r.cron.DeleteFromSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if cron.Status { if err := r.cron.AddToSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Delete 删除计划任务 func (r *CronController) Delete(ctx http.Context) http.Response { var cron models.Cron if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") } if err := r.cron.DeleteFromSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := io.Remove(cron.Shell); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if _, err := facades.Orm().Query().Delete(&cron); err != nil { facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{ "error": err.Error(), }).Info("删除计划任务失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Status 更新计划任务状态 func (r *CronController) Status(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "status": "bool", }); sanitize != nil { return sanitize @@ -252,7 +253,7 @@ func (r *CronController) Status(ctx http.Context) http.Response { var cron models.Cron if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") } cron.Status = ctx.Request().InputBool("status") @@ -260,36 +261,36 @@ func (r *CronController) Status(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{ "error": err.Error(), }).Info("更新计划任务状态失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := r.cron.DeleteFromSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if cron.Status { if err := r.cron.AddToSystem(cron); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Log 获取计划任务日志 func (r *CronController) Log(ctx http.Context) http.Response { var cron models.Cron if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil { - return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在") } if !io.Exists(cron.Log) { - return Error(ctx, http.StatusUnprocessableEntity, "日志文件不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "日志文件不存在") } log, err := shell.Execf("tail -n 1000 " + cron.Log) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, log) + return h.Success(ctx, log) } diff --git a/app/http/controllers/file_controller.go b/app/http/controllers/file_controller.go index 3e811e4d..d85e81d8 100644 --- a/app/http/controllers/file_controller.go +++ b/app/http/controllers/file_controller.go @@ -13,6 +13,7 @@ import ( "github.com/goravel/framework/support/carbon" requests "github.com/TheTNB/panel/v2/app/http/requests/file" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -39,7 +40,7 @@ func NewFileController() *FileController { // @Router /panel/file/create [post] func (r *FileController) Create(ctx http.Context) http.Response { var request requests.NotExist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } @@ -47,16 +48,16 @@ func (r *FileController) Create(ctx http.Context) http.Response { isDir := ctx.Request().InputBool("dir") if !isDir { if out, err := shell.Execf("touch " + request.Path); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if err := io.Mkdir(request.Path, 0755); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } r.setPermission(request.Path, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Content @@ -72,28 +73,28 @@ func (r *FileController) Create(ctx http.Context) http.Response { // @Router /panel/file/content [get] func (r *FileController) Content(ctx http.Context) http.Response { var request requests.Exist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } fileInfo, err := io.FileInfo(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if fileInfo.IsDir() { - return Error(ctx, http.StatusInternalServerError, "目标路径不是文件") + return h.Error(ctx, http.StatusInternalServerError, "目标路径不是文件") } if fileInfo.Size() > 10*1024*1024 { - return Error(ctx, http.StatusInternalServerError, "文件大小超过 10 M,不支持在线编辑") + return h.Error(ctx, http.StatusInternalServerError, "文件大小超过 10 M,不支持在线编辑") } content, err := io.Read(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, content) + return h.Success(ctx, content) } // Save @@ -109,21 +110,21 @@ func (r *FileController) Content(ctx http.Context) http.Response { // @Router /panel/file/save [post] func (r *FileController) Save(ctx http.Context) http.Response { var request requests.Save - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } fileInfo, err := io.FileInfo(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = io.Write(request.Path, request.Content, fileInfo.Mode()); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.Path, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Delete @@ -139,16 +140,16 @@ func (r *FileController) Save(ctx http.Context) http.Response { // @Router /panel/file/delete [post] func (r *FileController) Delete(ctx http.Context) http.Response { var request requests.Exist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } if err := io.Remove(request.Path); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Upload @@ -165,32 +166,32 @@ func (r *FileController) Delete(ctx http.Context) http.Response { // @Router /panel/file/upload [post] func (r *FileController) Upload(ctx http.Context) http.Response { var request requests.Upload - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } src, err := request.File.Open() if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } defer src.Close() if io.Exists(request.Path) && !ctx.Request().InputBool("force") { - return Error(ctx, http.StatusForbidden, "目标路径已存在,是否覆盖?") + return h.Error(ctx, http.StatusForbidden, "目标路径已存在,是否覆盖?") } data, err := stdio.ReadAll(src) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = io.Write(request.Path, string(data), 0755); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.Path, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Move @@ -206,21 +207,21 @@ func (r *FileController) Upload(ctx http.Context) http.Response { // @Router /panel/file/move [post] func (r *FileController) Move(ctx http.Context) http.Response { var request requests.Move - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } if io.Exists(request.Target) && !ctx.Request().InputBool("force") { - return Error(ctx, http.StatusForbidden, "目标路径"+request.Target+"已存在") + return h.Error(ctx, http.StatusForbidden, "目标路径"+request.Target+"已存在") } if err := io.Mv(request.Source, request.Target); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.Target, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Copy @@ -236,21 +237,21 @@ func (r *FileController) Move(ctx http.Context) http.Response { // @Router /panel/file/copy [post] func (r *FileController) Copy(ctx http.Context) http.Response { var request requests.Copy - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } if io.Exists(request.Target) && !ctx.Request().InputBool("force") { - return Error(ctx, http.StatusForbidden, "目标路径"+request.Target+"已存在") + return h.Error(ctx, http.StatusForbidden, "目标路径"+request.Target+"已存在") } if err := io.Cp(request.Source, request.Target); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.Source, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Download @@ -266,17 +267,17 @@ func (r *FileController) Copy(ctx http.Context) http.Response { // @Router /panel/file/download [get] func (r *FileController) Download(ctx http.Context) http.Response { var request requests.Exist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } info, err := io.FileInfo(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if info.IsDir() { - return Error(ctx, http.StatusInternalServerError, "不能下载目录") + return h.Error(ctx, http.StatusInternalServerError, "不能下载目录") } return ctx.Response().Download(request.Path, info.Name()) @@ -295,7 +296,7 @@ func (r *FileController) Download(ctx http.Context) http.Response { // @Router /panel/file/remoteDownload [post] func (r *FileController) RemoteDownload(ctx http.Context) http.Response { var request requests.NotExist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } @@ -317,17 +318,17 @@ func (r *FileController) RemoteDownload(ctx http.Context) http.Response { // @Router /panel/file/info [get] func (r *FileController) Info(ctx http.Context) http.Response { var request requests.Exist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } fileInfo, err := io.FileInfo(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "name": fileInfo.Name(), "size": str.FormatBytes(float64(fileInfo.Size())), "mode_str": fileInfo.Mode().String(), @@ -350,7 +351,7 @@ func (r *FileController) Info(ctx http.Context) http.Response { // @Router /panel/file/permission [post] func (r *FileController) Permission(ctx http.Context) http.Response { var request requests.Permission - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } @@ -358,17 +359,17 @@ func (r *FileController) Permission(ctx http.Context) http.Response { // 解析成8进制 mode, err := strconv.ParseUint(request.Mode, 8, 64) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = io.Chmod(request.Path, stdos.FileMode(mode)); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = io.Chown(request.Path, request.Owner, request.Group); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Archive @@ -384,17 +385,17 @@ func (r *FileController) Permission(ctx http.Context) http.Response { // @Router /panel/file/archive [post] func (r *FileController) Archive(ctx http.Context) http.Response { var request requests.Archive - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } if err := io.Archive(request.Paths, request.File); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.File, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // UnArchive @@ -410,17 +411,17 @@ func (r *FileController) Archive(ctx http.Context) http.Response { // @Router /panel/file/unArchive [post] func (r *FileController) UnArchive(ctx http.Context) http.Response { var request requests.UnArchive - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } if err := io.UnArchive(request.File, request.Path); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } r.setPermission(request.Path, 0755, "www", "www") - return Success(ctx, nil) + return h.Success(ctx, nil) } // Search @@ -435,7 +436,7 @@ func (r *FileController) UnArchive(ctx http.Context) http.Response { // @Router /panel/file/search [post] func (r *FileController) Search(ctx http.Context) http.Response { var request requests.Search - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } @@ -451,10 +452,10 @@ func (r *FileController) Search(ctx http.Context) http.Response { return nil }) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, paths) + return h.Success(ctx, paths) } // List @@ -470,14 +471,14 @@ func (r *FileController) Search(ctx http.Context) http.Response { // @Router /panel/file/list [get] func (r *FileController) List(ctx http.Context) http.Response { var request requests.Exist - sanitize := SanitizeRequest(ctx, &request) + sanitize := h.SanitizeRequest(ctx, &request) if sanitize != nil { return sanitize } fileInfoList, err := io.ReadDir(request.Path) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } var paths []any @@ -503,9 +504,9 @@ func (r *FileController) List(ctx http.Context) http.Response { }) } - paged, total := Paginate(ctx, paths) + paged, total := h.Paginate(ctx, paths) - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) diff --git a/app/http/controllers/info_controller.go b/app/http/controllers/info_controller.go index 2c020910..b3c07812 100644 --- a/app/http/controllers/info_controller.go +++ b/app/http/controllers/info_controller.go @@ -13,6 +13,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/systemctl" "github.com/TheTNB/panel/v2/pkg/tools" @@ -40,7 +41,7 @@ func NewInfoController() *InfoController { // Panel 获取面板信息 func (r *InfoController) Panel(ctx http.Context) http.Response { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "name": r.setting.Get(models.SettingKeyName), "language": facades.Config().GetString("app.locale"), }) @@ -54,7 +55,7 @@ func (r *InfoController) HomePlugins(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "基础信息").With(map[string]any{ "error": err.Error(), }).Info("获取首页插件失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } type pluginsData struct { @@ -70,19 +71,19 @@ func (r *InfoController) HomePlugins(ctx http.Context) http.Response { }) } - return Success(ctx, pluginsJson) + return h.Success(ctx, pluginsJson) } // NowMonitor 获取当前监控信息 func (r *InfoController) NowMonitor(ctx http.Context) http.Response { - return Success(ctx, tools.GetMonitoringInfo()) + return h.Success(ctx, tools.GetMonitoringInfo()) } // SystemInfo 获取系统信息 func (r *InfoController) SystemInfo(ctx http.Context) http.Response { monitorInfo := tools.GetMonitoringInfo() - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "os_name": monitorInfo.Host.Platform + " " + monitorInfo.Host.PlatformVersion, "uptime": fmt.Sprintf("%.2f", float64(monitorInfo.Host.Uptime)/86400), "panel_version": facades.Config().GetString("panel.version"), @@ -189,7 +190,7 @@ func (r *InfoController) CountInfo(ctx http.Context) http.Response { cronCount = -1 } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "website": websiteCount, "database": databaseCount, "ftp": ftpCount, @@ -202,7 +203,7 @@ func (r *InfoController) InstalledDbAndPhp(ctx http.Context) http.Response { var php []models.Plugin err := facades.Orm().Query().Where("slug like ?", "php%").Find(&php) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } var mysql models.Plugin @@ -243,7 +244,7 @@ func (r *InfoController) InstalledDbAndPhp(ctx http.Context) http.Response { dbData = append(dbData, data{Value: "postgresql", Label: "PostgreSQL"}) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "php": phpData, "db": dbData, }) @@ -254,24 +255,24 @@ func (r *InfoController) CheckUpdate(ctx http.Context) http.Response { current := facades.Config().GetString("panel.version") latest, err := tools.GetLatestPanelVersion() if err != nil { - return Error(ctx, http.StatusInternalServerError, "获取最新版本失败") + return h.Error(ctx, http.StatusInternalServerError, "获取最新版本失败") } v1, err := version.NewVersion(current) if err != nil { - return Error(ctx, http.StatusInternalServerError, "版本号解析失败") + return h.Error(ctx, http.StatusInternalServerError, "版本号解析失败") } v2, err := version.NewVersion(latest.Version) if err != nil { - return Error(ctx, http.StatusInternalServerError, "版本号解析失败") + return h.Error(ctx, http.StatusInternalServerError, "版本号解析失败") } if v1.GreaterThanOrEqual(v2) { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "update": false, }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "update": true, }) } @@ -281,24 +282,24 @@ func (r *InfoController) UpdateInfo(ctx http.Context) http.Response { current := facades.Config().GetString("panel.version") latest, err := tools.GetLatestPanelVersion() if err != nil { - return Error(ctx, http.StatusInternalServerError, "获取最新版本失败") + return h.Error(ctx, http.StatusInternalServerError, "获取最新版本失败") } v1, err := version.NewVersion(current) if err != nil { - return Error(ctx, http.StatusInternalServerError, "版本号解析失败") + return h.Error(ctx, http.StatusInternalServerError, "版本号解析失败") } v2, err := version.NewVersion(latest.Version) if err != nil { - return Error(ctx, http.StatusInternalServerError, "版本号解析失败") + return h.Error(ctx, http.StatusInternalServerError, "版本号解析失败") } if v1.GreaterThanOrEqual(v2) { - return Error(ctx, http.StatusInternalServerError, "当前版本已是最新版本") + return h.Error(ctx, http.StatusInternalServerError, "当前版本已是最新版本") } versions, err := tools.GenerateVersions(current, latest.Version) if err != nil { - return Error(ctx, http.StatusInternalServerError, "获取更新信息失败") + return h.Error(ctx, http.StatusInternalServerError, "获取更新信息失败") } var versionInfo []tools.PanelInfo @@ -311,18 +312,18 @@ func (r *InfoController) UpdateInfo(ctx http.Context) http.Response { versionInfo = append(versionInfo, info) } - return Success(ctx, versionInfo) + return h.Success(ctx, versionInfo) } // Update 更新面板 func (r *InfoController) Update(ctx http.Context) http.Response { var task models.Task if err := facades.Orm().Query().Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).FirstOrFail(&task); err == nil { - return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止更新") + return h.Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止更新") } if _, err := facades.Orm().Query().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { types.Status = types.StatusFailed - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("面板数据库异常,已终止操作:%s", err.Error())) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("面板数据库异常,已终止操作:%s", err.Error())) } panel, err := tools.GetLatestPanelVersion() @@ -330,7 +331,7 @@ func (r *InfoController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "基础信息").With(map[string]any{ "error": err.Error(), }).Info("获取最新版本失败") - return Error(ctx, http.StatusInternalServerError, "获取最新版本失败") + return h.Error(ctx, http.StatusInternalServerError, "获取最新版本失败") } types.Status = types.StatusUpgrade @@ -339,12 +340,12 @@ func (r *InfoController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "基础信息").With(map[string]any{ "error": err.Error(), }).Info("更新面板失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } types.Status = types.StatusNormal tools.RestartPanel() - return Success(ctx, nil) + return h.Success(ctx, nil) } // Restart 重启面板 @@ -352,9 +353,9 @@ func (r *InfoController) Restart(ctx http.Context) http.Response { var task models.Task err := facades.Orm().Query().Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).FirstOrFail(&task) if err == nil { - return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止重启") + return h.Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止重启") } tools.RestartPanel() - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/monitor_controller.go b/app/http/controllers/monitor_controller.go index 1c2565b0..4eb4140b 100644 --- a/app/http/controllers/monitor_controller.go +++ b/app/http/controllers/monitor_controller.go @@ -11,6 +11,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" ) type MonitorController struct { @@ -32,10 +33,10 @@ func (r *MonitorController) Switch(ctx http.Context) http.Response { "monitor": value, "error": err.Error(), }).Info("更新监控开关失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // SaveDays 保存监控天数 @@ -47,10 +48,10 @@ func (r *MonitorController) SaveDays(ctx http.Context) http.Response { "days": days, "error": err.Error(), }).Info("更新监控开关失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // SwitchAndDays 监控开关和监控天数 @@ -58,7 +59,7 @@ func (r *MonitorController) SwitchAndDays(ctx http.Context) http.Response { monitor := r.setting.Get(models.SettingKeyMonitor) monitorDays := r.setting.Get(models.SettingKeyMonitorDays) - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "switch": cast.ToBool(monitor), "days": cast.ToInt(monitorDays), }) @@ -71,10 +72,10 @@ func (r *MonitorController) Clear(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "资源监控").With(map[string]any{ "error": err.Error(), }).Info("清空监控数据失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // List 监控数据列表 @@ -92,11 +93,11 @@ func (r *MonitorController) List(ctx http.Context) http.Response { "end": endTime.ToDateTimeString(), "error": err.Error(), }).Info("获取监控数据失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if len(monitors) == 0 { - return Error(ctx, http.StatusNotFound, "监控数据为空") + return h.Error(ctx, http.StatusNotFound, "监控数据为空") } type load struct { @@ -181,5 +182,5 @@ func (r *MonitorController) List(ctx http.Context) http.Response { bytesRecv2 = 0 } - return Success(ctx, data) + return h.Success(ctx, data) } diff --git a/app/http/controllers/plugin_controller.go b/app/http/controllers/plugin_controller.go index c1ef9dca..5c6e56a4 100644 --- a/app/http/controllers/plugin_controller.go +++ b/app/http/controllers/plugin_controller.go @@ -7,6 +7,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" ) type PluginController struct { @@ -33,7 +34,7 @@ func (r *PluginController) List(ctx http.Context) http.Response { plugins := r.plugin.All() installedPlugins, err := r.plugin.AllInstalled() if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } installedPluginsMap := make(map[string]models.Plugin) @@ -75,9 +76,9 @@ func (r *PluginController) List(ctx http.Context) http.Response { }) } - paged, total := Paginate(ctx, pluginArr) + paged, total := h.Paginate(ctx, pluginArr) - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -96,10 +97,10 @@ func (r *PluginController) Install(ctx http.Context) http.Response { slug := ctx.Request().Input("slug") if err := r.plugin.Install(slug); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, "任务已提交") + return h.Success(ctx, "任务已提交") } // Uninstall @@ -115,10 +116,10 @@ func (r *PluginController) Uninstall(ctx http.Context) http.Response { slug := ctx.Request().Input("slug") if err := r.plugin.Uninstall(slug); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, "任务已提交") + return h.Success(ctx, "任务已提交") } // Update @@ -134,10 +135,10 @@ func (r *PluginController) Update(ctx http.Context) http.Response { slug := ctx.Request().Input("slug") if err := r.plugin.Update(slug); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, "任务已提交") + return h.Success(ctx, "任务已提交") } // UpdateShow @@ -160,10 +161,10 @@ func (r *PluginController) UpdateShow(ctx http.Context) http.Response { "slug": slug, "err": err.Error(), }).Info("获取插件失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if plugin.ID == 0 { - return Error(ctx, http.StatusUnprocessableEntity, "插件未安装") + return h.Error(ctx, http.StatusUnprocessableEntity, "插件未安装") } plugin.Show = show @@ -172,10 +173,10 @@ func (r *PluginController) UpdateShow(ctx http.Context) http.Response { "slug": slug, "err": err.Error(), }).Info("更新插件失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, "操作成功") + return h.Success(ctx, "操作成功") } // IsInstalled @@ -193,13 +194,13 @@ func (r *PluginController) IsInstalled(ctx http.Context) http.Response { plugin := r.plugin.GetInstalledBySlug(slug) info := r.plugin.GetBySlug(slug) if plugin.Slug != slug { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "name": info.Name, "installed": false, }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "name": info.Name, "installed": true, }) diff --git a/app/http/controllers/plugins/fail2ban_controller.go b/app/http/controllers/plugins/fail2ban_controller.go index 778251ed..60070973 100644 --- a/app/http/controllers/plugins/fail2ban_controller.go +++ b/app/http/controllers/plugins/fail2ban_controller.go @@ -8,10 +8,10 @@ import ( "github.com/goravel/framework/facades" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -33,12 +33,12 @@ func NewFail2banController() *Fail2banController { func (r *Fail2banController) List(ctx http.Context) http.Response { raw, err := io.Read("/etc/fail2ban/jail.local") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } jailList := regexp.MustCompile(`\[(.*?)]`).FindAllStringSubmatch(raw, -1) if len(jailList) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "Fail2ban 规则为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "Fail2ban 规则为空") } var jails []types.Fail2banJail @@ -68,9 +68,9 @@ func (r *Fail2banController) List(ctx http.Context) http.Response { }) } - paged, total := controllers.Paginate(ctx, jails) + paged, total := h.Paginate(ctx, jails) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -78,7 +78,7 @@ func (r *Fail2banController) List(ctx http.Context) http.Response { // Add 添加 Fail2ban 规则 func (r *Fail2banController) Add(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required", "type": "required|in:website,service", "maxretry": "required", @@ -102,10 +102,10 @@ func (r *Fail2banController) Add(ctx http.Context) http.Response { raw, err := io.Read("/etc/fail2ban/jail.local") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } if (strings.Contains(raw, "["+jailName+"]") && jailType == "service") || (strings.Contains(raw, "["+jailWebsiteName+"]"+"-cc") && jailType == "website" && jailWebsiteMode == "cc") || (strings.Contains(raw, "["+jailWebsiteName+"]"+"-path") && jailType == "website" && jailWebsiteMode == "path") { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "规则已存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "规则已存在") } switch jailType { @@ -113,11 +113,11 @@ func (r *Fail2banController) Add(ctx http.Context) http.Response { var website models.Website err := facades.Orm().Query().Where("name", jailWebsiteName).FirstOrFail(&website) if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "网站不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "网站不存在") } config, err := r.website.GetConfig(website.ID) if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取网站配置失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取网站配置失败") } var ports string for _, port := range config.Ports { @@ -140,7 +140,7 @@ logpath = /www/wwwlogs/` + website.Name + `.log ` raw += rule if err = io.Write("/etc/fail2ban/jail.local", raw, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") } var filter string @@ -158,7 +158,7 @@ ignoreregex = ` } if err = io.Write("/etc/fail2ban/filter.d/haozi-"+jailWebsiteName+"-"+jailWebsiteMode+".conf", filter, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") } case "service": @@ -184,10 +184,10 @@ ignoreregex = filter = "pure-ftpd" port, err = shell.Execf(`cat /www/server/pure-ftpd/etc/pure-ftpd.conf | grep "Bind" | awk '{print $2}' | awk -F "," '{print $2}'`) default: - return controllers.Error(ctx, http.StatusUnprocessableEntity, "未知服务") + return h.Error(ctx, http.StatusUnprocessableEntity, "未知服务") } if len(port) == 0 || err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取服务端口失败,请检查是否安装") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取服务端口失败,请检查是否安装") } rule := ` @@ -205,15 +205,15 @@ logpath = ` + logPath + ` ` raw += rule if err := io.Write("/etc/fail2ban/jail.local", raw, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") } } if _, err := shell.Execf("fail2ban-client reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载配置失败") + return h.Error(ctx, http.StatusInternalServerError, "重载配置失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Delete 删除规则 @@ -221,44 +221,44 @@ func (r *Fail2banController) Delete(ctx http.Context) http.Response { jailName := ctx.Request().Input("name") raw, err := io.Read("/etc/fail2ban/jail.local") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } if !strings.Contains(raw, "["+jailName+"]") { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "规则不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "规则不存在") } rule := str.Cut(raw, "# "+jailName+"-START", "# "+jailName+"-END") raw = strings.Replace(raw, "\n# "+jailName+"-START"+rule+"# "+jailName+"-END", "", -1) raw = strings.TrimSpace(raw) if err := io.Write("/etc/fail2ban/jail.local", raw, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") } if _, err := shell.Execf("fail2ban-client reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载配置失败") + return h.Error(ctx, http.StatusInternalServerError, "重载配置失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // BanList 获取封禁列表 func (r *Fail2banController) BanList(ctx http.Context) http.Response { name := ctx.Request().Input("name") if len(name) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") + return h.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") } currentlyBan, err := shell.Execf(`fail2ban-client status %s | grep "Currently banned" | awk '{print $4}'`, name) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") } totalBan, err := shell.Execf(`fail2ban-client status %s | grep "Total banned" | awk '{print $4}'`, name) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") } bannedIp, err := shell.Execf(`fail2ban-client status %s | grep "Banned IP list" | awk -F ":" '{print $2}'`, name) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取封禁列表失败") } bannedIpList := strings.Split(bannedIp, " ") @@ -275,7 +275,7 @@ func (r *Fail2banController) BanList(ctx http.Context) http.Response { list = []map[string]string{} } - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "currently_ban": currentlyBan, "total_ban": totalBan, "baned_list": list, @@ -287,56 +287,56 @@ func (r *Fail2banController) Unban(ctx http.Context) http.Response { name := ctx.Request().Input("name") ip := ctx.Request().Input("ip") if len(name) == 0 || len(ip) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") + return h.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") } if _, err := shell.Execf("fail2ban-client set %s unbanip %s", name, ip); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "解封失败") + return h.Error(ctx, http.StatusInternalServerError, "解封失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SetWhiteList 设置白名单 func (r *Fail2banController) SetWhiteList(ctx http.Context) http.Response { ip := ctx.Request().Input("ip") if len(ip) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") + return h.Error(ctx, http.StatusUnprocessableEntity, "缺少参数") } raw, err := io.Read("/etc/fail2ban/jail.local") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } // 正则替换 reg := regexp.MustCompile(`ignoreip\s*=\s*.*\n`) if reg.MatchString(raw) { raw = reg.ReplaceAllString(raw, "ignoreip = "+ip+"\n") } else { - return controllers.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏") + return h.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏") } if err := io.Write("/etc/fail2ban/jail.local", raw, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Fail2ban规则失败") } if _, err := shell.Execf("fail2ban-client reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载配置失败") + return h.Error(ctx, http.StatusInternalServerError, "重载配置失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetWhiteList 获取白名单 func (r *Fail2banController) GetWhiteList(ctx http.Context) http.Response { raw, err := io.Read("/etc/fail2ban/jail.local") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } reg := regexp.MustCompile(`ignoreip\s*=\s*(.*)\n`) if reg.MatchString(raw) { ignoreIp := reg.FindStringSubmatch(raw)[1] - return controllers.Success(ctx, ignoreIp) + return h.Success(ctx, ignoreIp) } else { - return controllers.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏") + return h.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏") } } diff --git a/app/http/controllers/plugins/frp_controller.go b/app/http/controllers/plugins/frp_controller.go index fc937459..e199d8a1 100644 --- a/app/http/controllers/plugins/frp_controller.go +++ b/app/http/controllers/plugins/frp_controller.go @@ -5,8 +5,8 @@ import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" requests "github.com/TheTNB/panel/v2/app/http/requests/plugins/frp" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/systemctl" ) @@ -30,17 +30,17 @@ func NewFrpController() *FrpController { // @Router /plugins/frp/config [get] func (r *FrpController) GetConfig(ctx http.Context) http.Response { var serviceRequest requests.Service - sanitize := controllers.SanitizeRequest(ctx, &serviceRequest) + sanitize := h.SanitizeRequest(ctx, &serviceRequest) if sanitize != nil { return sanitize } config, err := io.Read(fmt.Sprintf("/www/server/frp/%s.toml", serviceRequest.Service)) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // UpdateConfig @@ -55,18 +55,18 @@ func (r *FrpController) GetConfig(ctx http.Context) http.Response { // @Router /plugins/frp/config [post] func (r *FrpController) UpdateConfig(ctx http.Context) http.Response { var updateRequest requests.UpdateConfig - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } if err := io.Write(fmt.Sprintf("/www/server/frp/%s.toml", updateRequest.Service), updateRequest.Config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Restart(updateRequest.Service); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/gitea_controller.go b/app/http/controllers/plugins/gitea_controller.go index 18070a55..ad361949 100644 --- a/app/http/controllers/plugins/gitea_controller.go +++ b/app/http/controllers/plugins/gitea_controller.go @@ -3,8 +3,8 @@ package plugins import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" requests "github.com/TheTNB/panel/v2/app/http/requests/plugins/gitea" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/systemctl" ) @@ -28,10 +28,10 @@ func NewGiteaController() *GiteaController { func (r *GiteaController) GetConfig(ctx http.Context) http.Response { config, err := io.Read("/www/server/gitea/app.ini") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // UpdateConfig @@ -46,18 +46,18 @@ func (r *GiteaController) GetConfig(ctx http.Context) http.Response { // @Router /plugins/gitea/config [post] func (r *GiteaController) UpdateConfig(ctx http.Context) http.Response { var updateRequest requests.UpdateConfig - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } if err := io.Write("/www/server/gitea/app.ini", updateRequest.Config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Restart("gitea"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/mysql_controller.go b/app/http/controllers/plugins/mysql_controller.go index 4daeeb8f..d2e60215 100644 --- a/app/http/controllers/plugins/mysql_controller.go +++ b/app/http/controllers/plugins/mysql_controller.go @@ -7,11 +7,11 @@ import ( "github.com/goravel/framework/contracts/http" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" "github.com/TheTNB/panel/v2/pkg/db" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -35,45 +35,45 @@ func NewMySQLController() *MySQLController { func (r *MySQLController) GetConfig(ctx http.Context) http.Response { config, err := io.Read("/www/server/mysql/conf/my.cnf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "获取MySQL配置失败") } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig 保存配置 func (r *MySQLController) SaveConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") } if err := io.Write("/www/server/mysql/conf/my.cnf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入MySQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "写入MySQL配置失败") } if err := systemctl.Reload("mysqld"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载MySQL失败") + return h.Error(ctx, http.StatusInternalServerError, "重载MySQL失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Load 获取负载 func (r *MySQLController) Load(ctx http.Context) http.Response { rootPassword := r.setting.Get(models.SettingKeyMysqlRootPassword) if len(rootPassword) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空") } status, _ := systemctl.Status("mysqld") if !status { - return controllers.Success(ctx, []types.NV{}) + return h.Success(ctx, []types.NV{}) } raw, err := shell.Execf("mysqladmin -uroot -p" + rootPassword + " extended-status 2>&1") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败") } var data []map[string]string @@ -123,61 +123,61 @@ func (r *MySQLController) Load(ctx http.Context) http.Response { bufferPoolReadRequests := cast.ToFloat64(data[12]["value"]) data[10]["value"] = fmt.Sprintf("%.2f%%", bufferPoolReadRequests/(bufferPoolReads+bufferPoolReadRequests)*100) - return controllers.Success(ctx, data) + return h.Success(ctx, data) } // ErrorLog 获取错误日志 func (r *MySQLController) ErrorLog(ctx http.Context) http.Response { log, err := shell.Execf("tail -n 100 /www/server/mysql/mysql-error.log") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, log) + return h.Error(ctx, http.StatusInternalServerError, log) } - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearErrorLog 清空错误日志 func (r *MySQLController) ClearErrorLog(ctx http.Context) http.Response { if out, err := shell.Execf("echo '' > /www/server/mysql/mysql-error.log"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SlowLog 获取慢查询日志 func (r *MySQLController) SlowLog(ctx http.Context) http.Response { log, err := shell.Execf("tail -n 100 /www/server/mysql/mysql-slow.log") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, log) + return h.Error(ctx, http.StatusInternalServerError, log) } - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearSlowLog 清空慢查询日志 func (r *MySQLController) ClearSlowLog(ctx http.Context) http.Response { if out, err := shell.Execf("echo '' > /www/server/mysql/mysql-slow.log"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetRootPassword 获取root密码 func (r *MySQLController) GetRootPassword(ctx http.Context) http.Response { rootPassword := r.setting.Get(models.SettingKeyMysqlRootPassword) if len(rootPassword) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空") } - return controllers.Success(ctx, rootPassword) + return h.Success(ctx, rootPassword) } // SetRootPassword 设置root密码 func (r *MySQLController) SetRootPassword(ctx http.Context) http.Response { rootPassword := ctx.Request().Input("password") if len(rootPassword) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码不能为空") } oldRootPassword := r.setting.Get(models.SettingKeyMysqlRootPassword) @@ -185,18 +185,18 @@ func (r *MySQLController) SetRootPassword(ctx http.Context) http.Response { if err != nil { // 尝试安全模式直接改密 if err = db.MySQLResetRootPassword(rootPassword); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } else { if err = mysql.UserPassword("root", rootPassword); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } if err = r.setting.Set(models.SettingKeyMysqlRootPassword, rootPassword); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("设置保存失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("设置保存失败: %v", err)) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DatabaseList 获取数据库列表 @@ -204,7 +204,7 @@ func (r *MySQLController) DatabaseList(ctx http.Context) http.Response { password := r.setting.Get(models.SettingKeyMysqlRootPassword) mysql, err := db.NewMySQL("root", password, r.getSock(), "unix") if err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []types.MySQLDatabase{}, }) @@ -212,11 +212,11 @@ func (r *MySQLController) DatabaseList(ctx http.Context) http.Response { databases, err := mysql.Databases() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败") } - paged, total := controllers.Paginate(ctx, databases) + paged, total := h.Paginate(ctx, databases) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -224,7 +224,7 @@ func (r *MySQLController) DatabaseList(ctx http.Context) http.Response { // AddDatabase 添加数据库 func (r *MySQLController) AddDatabase(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$", "user": "required|min_len:1|max_len:32|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:32", @@ -239,24 +239,24 @@ func (r *MySQLController) AddDatabase(ctx http.Context) http.Response { mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.DatabaseCreate(database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.UserCreate(user, password); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.PrivilegesGrant(user, database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteDatabase 删除数据库 func (r *MySQLController) DeleteDatabase(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys", }); sanitize != nil { return sanitize @@ -266,25 +266,25 @@ func (r *MySQLController) DeleteDatabase(ctx http.Context) http.Response { database := ctx.Request().Input("database") mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.DatabaseDrop(database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // BackupList 获取备份列表 func (r *MySQLController) BackupList(ctx http.Context) http.Response { backups, err := r.backup.MysqlList() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := controllers.Paginate(ctx, backups) + paged, total := h.Paginate(ctx, backups) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -294,7 +294,7 @@ func (r *MySQLController) BackupList(ctx http.Context) http.Response { func (r *MySQLController) UploadBackup(ctx http.Context) http.Response { file, err := ctx.Request().File("file") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") } backupPath := r.setting.Get(models.SettingKeyBackupPath) + "/mysql" @@ -307,15 +307,15 @@ func (r *MySQLController) UploadBackup(ctx http.Context) http.Response { name := file.GetClientOriginalName() _, err = file.StoreAs(backupPath, name) if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // CreateBackup 创建备份 func (r *MySQLController) CreateBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys", }); sanitize != nil { return sanitize @@ -323,15 +323,15 @@ func (r *MySQLController) CreateBackup(ctx http.Context) http.Response { database := ctx.Request().Input("database") if err := r.backup.MysqlBackup(database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteBackup 删除备份 func (r *MySQLController) DeleteBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required|min_len:1|max_len:255", }); sanitize != nil { return sanitize @@ -340,15 +340,15 @@ func (r *MySQLController) DeleteBackup(ctx http.Context) http.Response { backupPath := r.setting.Get(models.SettingKeyBackupPath) + "/mysql" fileName := ctx.Request().Input("name") if err := io.Remove(backupPath + "/" + fileName); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // RestoreBackup 还原备份 func (r *MySQLController) RestoreBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "backup": "required|min_len:1|max_len:255", "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys", }); sanitize != nil { @@ -356,10 +356,10 @@ func (r *MySQLController) RestoreBackup(ctx http.Context) http.Response { } if err := r.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup")); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // UserList 用户列表 @@ -367,7 +367,7 @@ func (r *MySQLController) UserList(ctx http.Context) http.Response { password := r.setting.Get(models.SettingKeyMysqlRootPassword) mysql, err := db.NewMySQL("root", password, r.getSock(), "unix") if err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []types.MySQLUser{}, }) @@ -375,11 +375,11 @@ func (r *MySQLController) UserList(ctx http.Context) http.Response { users, err := mysql.Users() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取用户列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取用户列表失败") } - paged, total := controllers.Paginate(ctx, users) + paged, total := h.Paginate(ctx, users) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -387,7 +387,7 @@ func (r *MySQLController) UserList(ctx http.Context) http.Response { // AddUser 添加用户 func (r *MySQLController) AddUser(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$", "user": "required|min_len:1|max_len:32|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:32", @@ -401,21 +401,21 @@ func (r *MySQLController) AddUser(ctx http.Context) http.Response { database := ctx.Request().Input("database") mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.UserCreate(user, password); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.PrivilegesGrant(user, database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteUser 删除用户 func (r *MySQLController) DeleteUser(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "user": "required|min_len:1|max_len:32|regex:^[a-zA-Z0-9_]+$", }); sanitize != nil { return sanitize @@ -425,18 +425,18 @@ func (r *MySQLController) DeleteUser(ctx http.Context) http.Response { user := ctx.Request().Input("user") mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.UserDrop(user); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SetUserPassword 设置用户密码 func (r *MySQLController) SetUserPassword(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "user": "required|min_len:1|max_len:32|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:32", }); sanitize != nil { @@ -448,18 +448,18 @@ func (r *MySQLController) SetUserPassword(ctx http.Context) http.Response { password := ctx.Request().Input("password") mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.UserPassword(user, password); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SetUserPrivileges 设置用户权限 func (r *MySQLController) SetUserPrivileges(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "user": "required|min_len:1|max_len:32|regex:^[a-zA-Z0-9_]+$", "database": "required|min_len:1|max_len:64|regex:^[a-zA-Z0-9_]+$", }); sanitize != nil { @@ -471,13 +471,13 @@ func (r *MySQLController) SetUserPrivileges(ctx http.Context) http.Response { database := ctx.Request().Input("database") mysql, err := db.NewMySQL("root", rootPassword, r.getSock(), "unix") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = mysql.PrivilegesGrant(user, database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // getSock 获取sock文件位置 diff --git a/app/http/controllers/plugins/openresty_controller.go b/app/http/controllers/plugins/openresty_controller.go index c8301f9e..0795775f 100644 --- a/app/http/controllers/plugins/openresty_controller.go +++ b/app/http/controllers/plugins/openresty_controller.go @@ -9,7 +9,7 @@ import ( "github.com/goravel/framework/contracts/http" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -36,10 +36,10 @@ func NewOpenrestyController() *OpenRestyController { func (r *OpenRestyController) GetConfig(ctx http.Context) http.Response { config, err := io.Read("/www/server/openresty/conf/nginx.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取配置失败") + return h.Error(ctx, http.StatusInternalServerError, "获取配置失败") } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig @@ -54,19 +54,19 @@ func (r *OpenRestyController) GetConfig(ctx http.Context) http.Response { func (r *OpenRestyController) SaveConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "配置不能为空") + return h.Error(ctx, http.StatusInternalServerError, "配置不能为空") } if err := io.Write("/www/server/openresty/conf/nginx.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "保存配置失败") + return h.Error(ctx, http.StatusInternalServerError, "保存配置失败") } if err := systemctl.Reload("openresty"); err != nil { _, err = shell.Execf("openresty -t") - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载服务失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载服务失败: %v", err)) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ErrorLog @@ -79,15 +79,15 @@ func (r *OpenRestyController) SaveConfig(ctx http.Context) http.Response { // @Router /plugins/openresty/errorLog [get] func (r *OpenRestyController) ErrorLog(ctx http.Context) http.Response { if !io.Exists("/www/wwwlogs/nginx_error.log") { - return controllers.Success(ctx, "") + return h.Success(ctx, "") } out, err := shell.Execf("tail -n 100 /www/wwwlogs/openresty_error.log") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, out) + return h.Success(ctx, out) } // ClearErrorLog @@ -100,10 +100,10 @@ func (r *OpenRestyController) ErrorLog(ctx http.Context) http.Response { // @Router /plugins/openresty/clearErrorLog [post] func (r *OpenRestyController) ClearErrorLog(ctx http.Context) http.Response { if out, err := shell.Execf("echo '' > /www/wwwlogs/openresty_error.log"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Load @@ -118,7 +118,7 @@ func (r *OpenRestyController) Load(ctx http.Context) http.Response { client := resty.New().SetTimeout(10 * time.Second) resp, err := client.R().Get("http://127.0.0.1/nginx_status") if err != nil || !resp.IsSuccess() { - return controllers.Success(ctx, []types.NV{}) + return h.Success(ctx, []types.NV{}) } raw := resp.String() @@ -126,7 +126,7 @@ func (r *OpenRestyController) Load(ctx http.Context) http.Response { workers, err := shell.Execf("ps aux | grep nginx | grep 'worker process' | wc -l") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取负载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取负载失败") } data = append(data, types.NV{ Name: "工作进程", @@ -135,7 +135,7 @@ func (r *OpenRestyController) Load(ctx http.Context) http.Response { out, err := shell.Execf("ps aux | grep nginx | grep 'worker process' | awk '{memsum+=$6};END {print memsum}'") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取负载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取负载失败") } mem := str.FormatBytes(cast.ToFloat64(out)) data = append(data, types.NV{ @@ -183,5 +183,5 @@ func (r *OpenRestyController) Load(ctx http.Context) http.Response { }) } - return controllers.Success(ctx, data) + return h.Success(ctx, data) } diff --git a/app/http/controllers/plugins/php_controller.go b/app/http/controllers/plugins/php_controller.go index 82cb6b78..f14fd7e5 100644 --- a/app/http/controllers/plugins/php_controller.go +++ b/app/http/controllers/plugins/php_controller.go @@ -3,8 +3,8 @@ package plugins import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" ) type PHPController struct{} @@ -26,10 +26,10 @@ func (r *PHPController) GetConfig(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) config, err := service.GetConfig() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig @@ -46,10 +46,10 @@ func (r *PHPController) SaveConfig(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) config := ctx.Request().Input("config") if err := service.SaveConfig(config); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetFPMConfig @@ -65,10 +65,10 @@ func (r *PHPController) GetFPMConfig(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) config, err := service.GetFPMConfig() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveFPMConfig @@ -85,10 +85,10 @@ func (r *PHPController) SaveFPMConfig(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) config := ctx.Request().Input("config") if err := service.SaveFPMConfig(config); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Load @@ -104,10 +104,10 @@ func (r *PHPController) Load(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) load, err := service.Load() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, load) + return h.Success(ctx, load) } // ErrorLog @@ -122,7 +122,7 @@ func (r *PHPController) Load(ctx http.Context) http.Response { func (r *PHPController) ErrorLog(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) log, _ := service.GetErrorLog() - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // SlowLog @@ -137,7 +137,7 @@ func (r *PHPController) ErrorLog(ctx http.Context) http.Response { func (r *PHPController) SlowLog(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) log, _ := service.GetSlowLog() - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearErrorLog @@ -153,10 +153,10 @@ func (r *PHPController) ClearErrorLog(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) err := service.ClearErrorLog() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ClearSlowLog @@ -172,10 +172,10 @@ func (r *PHPController) ClearSlowLog(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) err := service.ClearSlowLog() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ExtensionList @@ -191,10 +191,10 @@ func (r *PHPController) ExtensionList(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) extensions, err := service.GetExtensions() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, extensions) + return h.Success(ctx, extensions) } // InstallExtension @@ -211,14 +211,14 @@ func (r *PHPController) InstallExtension(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) slug := ctx.Request().Input("slug") if len(slug) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } if err := service.InstallExtension(slug); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // UninstallExtension @@ -235,12 +235,12 @@ func (r *PHPController) UninstallExtension(ctx http.Context) http.Response { service := services.NewPHPImpl(uint(ctx.Request().RouteInt("version"))) slug := ctx.Request().Input("slug") if len(slug) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } if err := service.UninstallExtension(slug); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/phpmyadmin_controller.go b/app/http/controllers/plugins/phpmyadmin_controller.go index e777b1a8..d0c386d5 100644 --- a/app/http/controllers/plugins/phpmyadmin_controller.go +++ b/app/http/controllers/plugins/phpmyadmin_controller.go @@ -9,7 +9,7 @@ import ( "github.com/goravel/framework/facades" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -26,7 +26,7 @@ func NewPhpMyAdminController() *PhpMyAdminController { func (r *PhpMyAdminController) Info(ctx http.Context) http.Response { files, err := io.ReadDir("/www/server/phpmyadmin") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 目录") + return h.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 目录") } var phpmyadmin string @@ -36,19 +36,19 @@ func (r *PhpMyAdminController) Info(ctx http.Context) http.Response { } } if len(phpmyadmin) == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 目录") + return h.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 目录") } conf, err := io.Read("/www/server/vhost/phpmyadmin.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } match := regexp.MustCompile(`listen\s+(\d+);`).FindStringSubmatch(conf) if len(match) == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 端口") + return h.Error(ctx, http.StatusInternalServerError, "找不到 phpMyAdmin 端口") } - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "path": phpmyadmin, "port": cast.ToInt(match[1]), }) @@ -57,71 +57,71 @@ func (r *PhpMyAdminController) Info(ctx http.Context) http.Response { func (r *PhpMyAdminController) SetPort(ctx http.Context) http.Response { port := ctx.Request().InputInt("port") if port == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "端口不能为空") + return h.Error(ctx, http.StatusInternalServerError, "端口不能为空") } conf, err := io.Read("/www/server/vhost/phpmyadmin.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } conf = regexp.MustCompile(`listen\s+(\d+);`).ReplaceAllString(conf, "listen "+cast.ToString(port)+";") if err := io.Write("/www/server/vhost/phpmyadmin.conf", conf, 0644); err != nil { facades.Log().Request(ctx.Request()).Tags("插件", "phpMyAdmin").With(map[string]any{ "error": err.Error(), }).Info("修改 phpMyAdmin 端口失败") - return controllers.ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if os.IsRHEL() { if out, err := shell.Execf("firewall-cmd --zone=public --add-port=%d/tcp --permanent", port); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if out, err := shell.Execf("ufw allow %d/tcp", port); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } if err = systemctl.Reload("openresty"); err != nil { _, err = shell.Execf("openresty -t") - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } func (r *PhpMyAdminController) GetConfig(ctx http.Context) http.Response { config, err := io.Read("/www/server/vhost/phpmyadmin.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } func (r *PhpMyAdminController) SaveConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "配置不能为空") + return h.Error(ctx, http.StatusInternalServerError, "配置不能为空") } if err := io.Write("/www/server/vhost/phpmyadmin.conf", config, 0644); err != nil { facades.Log().Request(ctx.Request()).Tags("插件", "phpMyAdmin").With(map[string]any{ "error": err.Error(), }).Info("修改 phpMyAdmin 配置失败") - return controllers.ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := systemctl.Reload("openresty"); err != nil { _, err = shell.Execf("openresty -t") - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/podman_controller.go b/app/http/controllers/plugins/podman_controller.go index 0d130671..d5bddcef 100644 --- a/app/http/controllers/plugins/podman_controller.go +++ b/app/http/controllers/plugins/podman_controller.go @@ -3,8 +3,8 @@ package plugins import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" requests "github.com/TheTNB/panel/v2/app/http/requests/plugins/podman" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/systemctl" ) @@ -28,10 +28,10 @@ func NewPodmanController() *PodmanController { func (r *PodmanController) GetRegistryConfig(ctx http.Context) http.Response { config, err := io.Read("/etc/containers/registries.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // UpdateRegistryConfig @@ -46,20 +46,20 @@ func (r *PodmanController) GetRegistryConfig(ctx http.Context) http.Response { // @Router /plugins/podman/registryConfig [post] func (r *PodmanController) UpdateRegistryConfig(ctx http.Context) http.Response { var updateRequest requests.UpdateRegistryConfig - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } if err := io.Write("/etc/containers/registries.conf", updateRequest.Config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Restart("podman"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetStorageConfig @@ -74,10 +74,10 @@ func (r *PodmanController) UpdateRegistryConfig(ctx http.Context) http.Response func (r *PodmanController) GetStorageConfig(ctx http.Context) http.Response { config, err := io.Read("/etc/containers/storage.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // UpdateStorageConfig @@ -92,18 +92,18 @@ func (r *PodmanController) GetStorageConfig(ctx http.Context) http.Response { // @Router /plugins/podman/storageConfig [post] func (r *PodmanController) UpdateStorageConfig(ctx http.Context) http.Response { var updateRequest requests.UpdateStorageConfig - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } if err := io.Write("/etc/containers/storage.conf", updateRequest.Config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Restart("podman"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/postgresql_controller.go b/app/http/controllers/plugins/postgresql_controller.go index f73eb7f0..55b76c51 100644 --- a/app/http/controllers/plugins/postgresql_controller.go +++ b/app/http/controllers/plugins/postgresql_controller.go @@ -7,10 +7,10 @@ import ( "github.com/goravel/framework/support/carbon" _ "github.com/lib/pq" - "github.com/TheTNB/panel/v2/app/http/controllers" "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/systemctl" @@ -34,10 +34,10 @@ func (r *PostgreSQLController) GetConfig(ctx http.Context) http.Response { // 获取配置 config, err := io.Read("/www/server/postgresql/data/postgresql.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败") } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // GetUserConfig 获取用户配置 @@ -45,74 +45,74 @@ func (r *PostgreSQLController) GetUserConfig(ctx http.Context) http.Response { // 获取配置 config, err := io.Read("/www/server/postgresql/data/pg_hba.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败") } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig 保存配置 func (r *PostgreSQLController) SaveConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") } if err := io.Write("/www/server/postgresql/data/postgresql.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败") } if err := systemctl.Reload("postgresql"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载服务失败") + return h.Error(ctx, http.StatusInternalServerError, "重载服务失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SaveUserConfig 保存用户配置 func (r *PostgreSQLController) SaveUserConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") } if err := io.Write("/www/server/postgresql/data/pg_hba.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败") + return h.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败") } if err := systemctl.Reload("postgresql"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载服务失败") + return h.Error(ctx, http.StatusInternalServerError, "重载服务失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Load 获取负载 func (r *PostgreSQLController) Load(ctx http.Context) http.Response { status, _ := systemctl.Status("postgresql") if !status { - return controllers.Success(ctx, []types.NV{}) + return h.Success(ctx, []types.NV{}) } time, err := shell.Execf(`echo "select pg_postmaster_start_time();" | su - postgres -c "psql" | sed -n 3p | cut -d'.' -f1`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL启动时间失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL启动时间失败") } pid, err := shell.Execf(`echo "select pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL进程PID失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL进程PID失败") } process, err := shell.Execf(`ps aux | grep postgres | grep -v grep | wc -l`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL进程数失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL进程数失败") } connections, err := shell.Execf(`echo "SELECT count(*) FROM pg_stat_activity WHERE NOT pid=pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL连接数失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL连接数失败") } storage, err := shell.Execf(`echo "select pg_size_pretty(pg_database_size('postgres'));" | su - postgres -c "psql" | sed -n 3p`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL空间占用失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL空间占用失败") } data := []types.NV{ @@ -123,26 +123,26 @@ func (r *PostgreSQLController) Load(ctx http.Context) http.Response { {Name: "空间占用", Value: storage}, } - return controllers.Success(ctx, data) + return h.Success(ctx, data) } // Log 获取日志 func (r *PostgreSQLController) Log(ctx http.Context) http.Response { log, err := shell.Execf("tail -n 100 /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, log) + return h.Error(ctx, http.StatusInternalServerError, log) } - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearLog 清空日志 func (r *PostgreSQLController) ClearLog(ctx http.Context) http.Response { if out, err := shell.Execf("echo '' > /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DatabaseList 获取数据库列表 @@ -155,14 +155,14 @@ func (r *PostgreSQLController) DatabaseList(ctx http.Context) http.Response { db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres dbname=postgres sslmode=disable") if err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []database{}, }) } if err = db.Ping(); err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []database{}, }) @@ -175,7 +175,7 @@ func (r *PostgreSQLController) DatabaseList(ctx http.Context) http.Response { ` rows, err := db.Query(query) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } defer rows.Close() @@ -183,17 +183,17 @@ func (r *PostgreSQLController) DatabaseList(ctx http.Context) http.Response { for rows.Next() { var db database if err := rows.Scan(&db.Name, &db.Owner, &db.Encoding); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } databases = append(databases, db) } if err = rows.Err(); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := controllers.Paginate(ctx, databases) + paged, total := h.Paginate(ctx, databases) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -201,7 +201,7 @@ func (r *PostgreSQLController) DatabaseList(ctx http.Context) http.Response { // AddDatabase 添加数据库 func (r *PostgreSQLController) AddDatabase(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:63|regex:^[a-zA-Z0-9_]+$", "user": "required|min_len:1|max_len:30|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:40", @@ -214,33 +214,33 @@ func (r *PostgreSQLController) AddDatabase(ctx http.Context) http.Response { password := ctx.Request().Input("password") if out, err := shell.Execf(`echo "CREATE DATABASE ` + database + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`echo "ALTER DATABASE ` + database + ` OWNER TO ` + user + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256" if out, err := shell.Execf(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err := systemctl.Reload("postgresql"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载服务失败") + return h.Error(ctx, http.StatusInternalServerError, "重载服务失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteDatabase 删除数据库 func (r *PostgreSQLController) DeleteDatabase(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:63|regex:^[a-zA-Z0-9_]+$|not_in:postgres,template0,template1", }); sanitize != nil { return sanitize @@ -248,22 +248,22 @@ func (r *PostgreSQLController) DeleteDatabase(ctx http.Context) http.Response { database := ctx.Request().Input("database") if out, err := shell.Execf(`echo "DROP DATABASE ` + database + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // BackupList 获取备份列表 func (r *PostgreSQLController) BackupList(ctx http.Context) http.Response { backups, err := r.backup.PostgresqlList() if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败") + return h.Error(ctx, http.StatusInternalServerError, "获取备份列表失败") } - paged, total := controllers.Paginate(ctx, backups) + paged, total := h.Paginate(ctx, backups) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -273,7 +273,7 @@ func (r *PostgreSQLController) BackupList(ctx http.Context) http.Response { func (r *PostgreSQLController) UploadBackup(ctx http.Context) http.Response { file, err := ctx.Request().File("file") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") } backupPath := r.setting.Get(models.SettingKeyBackupPath) + "/postgresql" @@ -286,15 +286,15 @@ func (r *PostgreSQLController) UploadBackup(ctx http.Context) http.Response { name := file.GetClientOriginalName() _, err = file.StoreAs(backupPath, name) if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // CreateBackup 创建备份 func (r *PostgreSQLController) CreateBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:63|regex:^[a-zA-Z0-9_]+$|not_in:postgres,template0,template1", }); sanitize != nil { return sanitize @@ -302,15 +302,15 @@ func (r *PostgreSQLController) CreateBackup(ctx http.Context) http.Response { database := ctx.Request().Input("database") if err := r.backup.PostgresqlBackup(database); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteBackup 删除备份 func (r *PostgreSQLController) DeleteBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required|min_len:1|max_len:255", }); sanitize != nil { return sanitize @@ -319,15 +319,15 @@ func (r *PostgreSQLController) DeleteBackup(ctx http.Context) http.Response { backupPath := r.setting.Get(models.SettingKeyBackupPath) + "/postgresql" fileName := ctx.Request().Input("name") if err := io.Remove(backupPath + "/" + fileName); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // RestoreBackup 还原备份 func (r *PostgreSQLController) RestoreBackup(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "backup": "required|min_len:1|max_len:255", "database": "required|min_len:1|max_len:63|regex:^[a-zA-Z0-9_]+$|not_in:postgres,template0,template1", }); sanitize != nil { @@ -335,10 +335,10 @@ func (r *PostgreSQLController) RestoreBackup(ctx http.Context) http.Response { } if err := r.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup")); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error()) + return h.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // RoleList 角色列表 @@ -350,13 +350,13 @@ func (r *PostgreSQLController) RoleList(ctx http.Context) http.Response { db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres dbname=postgres sslmode=disable") if err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []role{}, }) } if err = db.Ping(); err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []role{}, }) @@ -374,7 +374,7 @@ func (r *PostgreSQLController) RoleList(ctx http.Context) http.Response { ` rows, err := db.Query(query) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } defer rows.Close() @@ -383,7 +383,7 @@ func (r *PostgreSQLController) RoleList(ctx http.Context) http.Response { var r role var super, canCreateRole, canCreateDb, replication, bypassRls bool if err = rows.Scan(&r.Role, &super, &canCreateRole, &canCreateDb, &replication, &bypassRls); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } permissions := map[string]bool{ @@ -406,12 +406,12 @@ func (r *PostgreSQLController) RoleList(ctx http.Context) http.Response { roles = append(roles, r) } if err = rows.Err(); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := controllers.Paginate(ctx, roles) + paged, total := h.Paginate(ctx, roles) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -419,7 +419,7 @@ func (r *PostgreSQLController) RoleList(ctx http.Context) http.Response { // AddRole 添加角色 func (r *PostgreSQLController) AddRole(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "database": "required|min_len:1|max_len:63|regex:^[a-zA-Z0-9_]+$", "user": "required|min_len:1|max_len:30|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:40", @@ -431,27 +431,27 @@ func (r *PostgreSQLController) AddRole(ctx http.Context) http.Response { password := ctx.Request().Input("password") database := ctx.Request().Input("database") if out, err := shell.Execf(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256" if out, err := shell.Execf(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err := systemctl.Reload("postgresql"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载服务失败") + return h.Error(ctx, http.StatusInternalServerError, "重载服务失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteRole 删除角色 func (r *PostgreSQLController) DeleteRole(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "user": "required|min_len:1|max_len:30|regex:^[a-zA-Z0-9_]+$", }); sanitize != nil { return sanitize @@ -459,22 +459,22 @@ func (r *PostgreSQLController) DeleteRole(ctx http.Context) http.Response { user := ctx.Request().Input("user") if out, err := shell.Execf(`echo "DROP USER ` + user + `;" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`sed -i '/` + user + `/d' /www/server/postgresql/data/pg_hba.conf`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err := systemctl.Reload("postgresql"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重载服务失败") + return h.Error(ctx, http.StatusInternalServerError, "重载服务失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SetRolePassword 设置用户密码 func (r *PostgreSQLController) SetRolePassword(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "user": "required|min_len:1|max_len:30|regex:^[a-zA-Z0-9_]+$", "password": "required|min_len:8|max_len:40", }); sanitize != nil { @@ -484,8 +484,8 @@ func (r *PostgreSQLController) SetRolePassword(ctx http.Context) http.Response { user := ctx.Request().Input("user") password := ctx.Request().Input("password") if out, err := shell.Execf(`echo "ALTER USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/pureftpd_controller.go b/app/http/controllers/plugins/pureftpd_controller.go index 60a9ec2a..79394c5d 100644 --- a/app/http/controllers/plugins/pureftpd_controller.go +++ b/app/http/controllers/plugins/pureftpd_controller.go @@ -7,7 +7,7 @@ import ( "github.com/goravel/framework/contracts/http" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -26,7 +26,7 @@ func NewPureFtpdController() *PureFtpdController { func (r *PureFtpdController) List(ctx http.Context) http.Response { listRaw, err := shell.Execf("pure-pw list") if err != nil { - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []types.PureFtpdUser{}, }) @@ -46,9 +46,9 @@ func (r *PureFtpdController) List(ctx http.Context) http.Response { }) } - paged, total := controllers.Paginate(ctx, users) + paged, total := h.Paginate(ctx, users) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -56,7 +56,7 @@ func (r *PureFtpdController) List(ctx http.Context) http.Response { // Add 添加用户 func (r *PureFtpdController) Add(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "username": "required", "password": "required|min_len:6", "path": "required", @@ -72,28 +72,28 @@ func (r *PureFtpdController) Add(ctx http.Context) http.Response { path = "/" + path } if !io.Exists(path) { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "目录不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "目录不存在") } if err := io.Chmod(path, 0755); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "修改目录权限失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "修改目录权限失败") } if err := io.Chown(path, "www", "www"); err != nil { return nil } if out, err := shell.Execf(`yes '` + password + `' | pure-pw useradd ` + username + ` -u www -g www -d ` + path); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("pure-pw mkdb"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Delete 删除用户 func (r *PureFtpdController) Delete(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "username": "required", }); sanitize != nil { return sanitize @@ -102,18 +102,18 @@ func (r *PureFtpdController) Delete(ctx http.Context) http.Response { username := ctx.Request().Input("username") if out, err := shell.Execf("pure-pw userdel " + username + " -m"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("pure-pw mkdb"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ChangePassword 修改密码 func (r *PureFtpdController) ChangePassword(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "username": "required", "password": "required|min_len:6", }); sanitize != nil { @@ -124,28 +124,28 @@ func (r *PureFtpdController) ChangePassword(ctx http.Context) http.Response { password := ctx.Request().Input("password") if out, err := shell.Execf(`yes '` + password + `' | pure-pw passwd ` + username + ` -m`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("pure-pw mkdb"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetPort 获取端口 func (r *PureFtpdController) GetPort(ctx http.Context) http.Response { port, err := shell.Execf(`cat /www/server/pure-ftpd/etc/pure-ftpd.conf | grep "Bind" | awk '{print $2}' | awk -F "," '{print $2}'`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd端口失败") + return h.Error(ctx, http.StatusInternalServerError, "获取PureFtpd端口失败") } - return controllers.Success(ctx, cast.ToInt(port)) + return h.Success(ctx, cast.ToInt(port)) } // SetPort 设置端口 func (r *PureFtpdController) SetPort(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "port": "required", }); sanitize != nil { return sanitize @@ -153,27 +153,27 @@ func (r *PureFtpdController) SetPort(ctx http.Context) http.Response { port := ctx.Request().Input("port") if out, err := shell.Execf(`sed -i "s/Bind.*/Bind 0.0.0.0,%s/g" /www/server/pure-ftpd/etc/pure-ftpd.conf`, port); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if os.IsRHEL() { if out, err := shell.Execf("firewall-cmd --zone=public --add-port=%s/tcp --permanent", port); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if out, err := shell.Execf("ufw allow %s/tcp", port); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw reload"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } if err := systemctl.Restart("pure-ftpd"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/redis_controller.go b/app/http/controllers/plugins/redis_controller.go index ecccf4a8..1e234182 100644 --- a/app/http/controllers/plugins/redis_controller.go +++ b/app/http/controllers/plugins/redis_controller.go @@ -5,7 +5,7 @@ import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/systemctl" @@ -24,43 +24,43 @@ func (r *RedisController) GetConfig(ctx http.Context) http.Response { // 获取配置 config, err := io.Read("/www/server/redis/redis.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis配置失败") + return h.Error(ctx, http.StatusInternalServerError, "获取Redis配置失败") } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig 保存配置 func (r *RedisController) SaveConfig(ctx http.Context) http.Response { config := ctx.Request().Input("config") if len(config) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空") } if err := io.Write("/www/server/redis/redis.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入Redis配置失败") + return h.Error(ctx, http.StatusInternalServerError, "写入Redis配置失败") } if err := systemctl.Restart("redis"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "重启Redis失败") + return h.Error(ctx, http.StatusInternalServerError, "重启Redis失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Load 获取负载 func (r *RedisController) Load(ctx http.Context) http.Response { status, err := systemctl.Status("redis") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败") + return h.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败") } if !status { - return controllers.Error(ctx, http.StatusInternalServerError, "Redis已停止运行") + return h.Error(ctx, http.StatusInternalServerError, "Redis已停止运行") } raw, err := shell.Execf("redis-cli info") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis负载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取Redis负载失败") } infoLines := strings.Split(raw, "\n") @@ -89,5 +89,5 @@ func (r *RedisController) Load(ctx http.Context) http.Response { {Name: "最近一次 fork() 操作耗费的毫秒数", Value: dataRaw["latest_fork_usec"]}, } - return controllers.Success(ctx, data) + return h.Success(ctx, data) } diff --git a/app/http/controllers/plugins/rsync_controller.go b/app/http/controllers/plugins/rsync_controller.go index fa16fa98..1c15b859 100644 --- a/app/http/controllers/plugins/rsync_controller.go +++ b/app/http/controllers/plugins/rsync_controller.go @@ -6,8 +6,8 @@ import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" requests "github.com/TheTNB/panel/v2/app/http/requests/plugins/rsync" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -35,7 +35,7 @@ func NewRsyncController() *RsyncController { func (r *RsyncController) List(ctx http.Context) http.Response { config, err := io.Read("/etc/rsyncd.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } var modules []types.RsyncModule @@ -74,7 +74,7 @@ func (r *RsyncController) List(ctx http.Context) http.Response { currentModule.AuthUser = value currentModule.Secret, err = shell.Execf("grep -E '^" + currentModule.AuthUser + ":.*$' /etc/rsyncd.secrets | awk -F ':' '{print $2}'") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取模块"+currentModule.AuthUser+"的密钥失败") + return h.Error(ctx, http.StatusInternalServerError, "获取模块"+currentModule.AuthUser+"的密钥失败") } case "hosts allow": currentModule.HostsAllow = value @@ -87,9 +87,9 @@ func (r *RsyncController) List(ctx http.Context) http.Response { modules = append(modules, *currentModule) } - paged, total := controllers.Paginate(ctx, modules) + paged, total := h.Paginate(ctx, modules) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -107,17 +107,17 @@ func (r *RsyncController) List(ctx http.Context) http.Response { // @Router /plugins/rsync/modules [post] func (r *RsyncController) Create(ctx http.Context) http.Response { var createRequest requests.Create - sanitize := controllers.SanitizeRequest(ctx, &createRequest) + sanitize := h.SanitizeRequest(ctx, &createRequest) if sanitize != nil { return sanitize } config, err := io.Read("/etc/rsyncd.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if strings.Contains(config, "["+createRequest.Name+"]") { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "模块 "+createRequest.Name+" 已存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "模块 "+createRequest.Name+" 已存在") } conf := `# ` + createRequest.Name + `-START @@ -132,17 +132,17 @@ secrets file = /etc/rsyncd.secrets ` if err := io.WriteAppend("/etc/rsyncd.conf", conf); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if out, err := shell.Execf("echo '" + createRequest.AuthUser + ":" + createRequest.Secret + "' >> /etc/rsyncd.secrets"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err := systemctl.Restart("rsyncd"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Destroy @@ -158,15 +158,15 @@ secrets file = /etc/rsyncd.secrets func (r *RsyncController) Destroy(ctx http.Context) http.Response { name := ctx.Request().Input("name") if len(name) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "name 不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "name 不能为空") } config, err := io.Read("/etc/rsyncd.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if !strings.Contains(config, "["+name+"]") { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "模块 "+name+" 不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "模块 "+name+" 不存在") } module := str.Cut(config, "# "+name+"-START", "# "+name+"-END") @@ -176,19 +176,19 @@ func (r *RsyncController) Destroy(ctx http.Context) http.Response { if len(match) == 2 { authUser := match[1] if out, err := shell.Execf("sed -i '/^" + authUser + ":.*$/d' /etc/rsyncd.secrets"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } if err = io.Write("/etc/rsyncd.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = systemctl.Restart("rsyncd"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Update @@ -204,17 +204,17 @@ func (r *RsyncController) Destroy(ctx http.Context) http.Response { // @Router /plugins/rsync/modules/{name} [post] func (r *RsyncController) Update(ctx http.Context) http.Response { var updateRequest requests.Update - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } config, err := io.Read("/etc/rsyncd.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if !strings.Contains(config, "["+updateRequest.Name+"]") { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "模块 "+updateRequest.Name+" 不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "模块 "+updateRequest.Name+" 不存在") } newConf := `# ` + updateRequest.Name + `-START @@ -234,22 +234,22 @@ secrets file = /etc/rsyncd.secrets if len(match) == 2 { authUser := match[1] if out, err := shell.Execf("sed -i '/^" + authUser + ":.*$/d' /etc/rsyncd.secrets"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } if err = io.Write("/etc/rsyncd.conf", config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if out, err := shell.Execf("echo '" + updateRequest.AuthUser + ":" + updateRequest.Secret + "' >> /etc/rsyncd.secrets"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if err = systemctl.Restart("rsyncd"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetConfig @@ -264,10 +264,10 @@ secrets file = /etc/rsyncd.secrets func (r *RsyncController) GetConfig(ctx http.Context) http.Response { config, err := io.Read("/etc/rsyncd.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // UpdateConfig @@ -282,18 +282,18 @@ func (r *RsyncController) GetConfig(ctx http.Context) http.Response { // @Router /plugins/rsync/config [post] func (r *RsyncController) UpdateConfig(ctx http.Context) http.Response { var updateRequest requests.UpdateConfig - sanitize := controllers.SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } if err := io.Write("/etc/rsyncd.conf", updateRequest.Config, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Restart("rsyncd"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/s3fs_controller.go b/app/http/controllers/plugins/s3fs_controller.go index 2a06a9ec..c16c1b3e 100644 --- a/app/http/controllers/plugins/s3fs_controller.go +++ b/app/http/controllers/plugins/s3fs_controller.go @@ -8,9 +8,9 @@ import ( "github.com/goravel/framework/support/json" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/types" @@ -31,12 +31,12 @@ func (r *S3fsController) List(ctx http.Context) http.Response { var s3fsList []types.S3fsMount err := json.UnmarshalString(r.setting.Get("s3fs", "[]"), &s3fsList) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") } - paged, total := controllers.Paginate(ctx, s3fsList) + paged, total := h.Paginate(ctx, s3fsList) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -44,7 +44,7 @@ func (r *S3fsController) List(ctx http.Context) http.Response { // Add 添加 S3fs 挂载 func (r *S3fsController) Add(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "ak": "required|regex:^[a-zA-Z0-9]*$", "sk": "required|regex:^[a-zA-Z0-9]*$", "bucket": "required|regex:^[a-zA-Z0-9_-]*$", @@ -62,27 +62,27 @@ func (r *S3fsController) Add(ctx http.Context) http.Response { // 检查下地域节点中是否包含bucket,如果包含了,肯定是错误的 if strings.Contains(url, bucket) { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "地域节点不能包含 Bucket 名称") + return h.Error(ctx, http.StatusUnprocessableEntity, "地域节点不能包含 Bucket 名称") } // 检查挂载目录是否存在且为空 if !io.Exists(path) { if err := io.Mkdir(path, 0755); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载目录创建失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "挂载目录创建失败") } } if !io.Empty(path) { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载目录必须为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "挂载目录必须为空") } var s3fsList []types.S3fsMount if err := json.UnmarshalString(r.setting.Get("s3fs", "[]"), &s3fsList); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") } for _, s := range s3fsList { if s.Path == path { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "路径已存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "路径已存在") } } @@ -93,15 +93,15 @@ func (r *S3fsController) Add(ctx http.Context) http.Response { } out, err := shell.Execf(`echo 's3fs#` + bucket + ` ` + path + ` fuse _netdev,allow_other,nonempty,url=` + url + `,passwd_file=/etc/passwd-s3fs-` + cast.ToString(id) + ` 0 0' >> /etc/fstab`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if mountCheck, err := shell.Execf("mount -a 2>&1"); err != nil { _, _ = shell.Execf(`sed -i 's@^s3fs#` + bucket + `\s` + path + `.*$@@g' /etc/fstab`) - return controllers.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck) + return h.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck) } if _, err := shell.Execf("df -h | grep " + path + " 2>&1"); err != nil { _, _ = shell.Execf(`sed -i 's@^s3fs#` + bucket + `\s` + path + `.*$@@g' /etc/fstab`) - return controllers.Error(ctx, http.StatusInternalServerError, "挂载失败,请检查配置是否正确") + return h.Error(ctx, http.StatusInternalServerError, "挂载失败,请检查配置是否正确") } s3fsList = append(s3fsList, types.S3fsMount{ @@ -112,27 +112,27 @@ func (r *S3fsController) Add(ctx http.Context) http.Response { }) encoded, err := json.MarshalString(s3fsList) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败") } err = r.setting.Set("s3fs", encoded) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Delete 删除 S3fs 挂载 func (r *S3fsController) Delete(ctx http.Context) http.Response { id := ctx.Request().Input("id") if len(id) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不能为空") } var s3fsList []types.S3fsMount err := json.UnmarshalString(r.setting.Get("s3fs", "[]"), &s3fsList) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败") } var mount types.S3fsMount @@ -143,23 +143,23 @@ func (r *S3fsController) Delete(ctx http.Context) http.Response { } } if mount.ID == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不存在") + return h.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不存在") } if out, err := shell.Execf(`fusermount -u '` + mount.Path + `' 2>&1`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`umount '` + mount.Path + `' 2>&1`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf(`sed -i 's@^s3fs#` + mount.Bucket + `\s` + mount.Path + `.*$@@g' /etc/fstab`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if mountCheck, err := shell.Execf("mount -a 2>&1"); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck) + return h.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck) } if err := io.Remove("/etc/passwd-s3fs-" + cast.ToString(mount.ID)); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } var newS3fsList []types.S3fsMount @@ -170,12 +170,12 @@ func (r *S3fsController) Delete(ctx http.Context) http.Response { } encoded, err := json.MarshalString(newS3fsList) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败") } err = r.setting.Set("s3fs", encoded) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败") + return h.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/supervisor_controller.go b/app/http/controllers/plugins/supervisor_controller.go index db030de5..4be32032 100644 --- a/app/http/controllers/plugins/supervisor_controller.go +++ b/app/http/controllers/plugins/supervisor_controller.go @@ -7,7 +7,7 @@ import ( "github.com/goravel/framework/contracts/http" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -33,26 +33,26 @@ func NewSupervisorController() *SupervisorController { // Service 获取服务名称 func (r *SupervisorController) Service(ctx http.Context) http.Response { - return controllers.Success(ctx, r.service) + return h.Success(ctx, r.service) } // Log 日志 func (r *SupervisorController) Log(ctx http.Context) http.Response { log, err := shell.Execf(`tail -n 200 /var/log/supervisor/supervisord.log`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, log) + return h.Error(ctx, http.StatusInternalServerError, log) } - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearLog 清空日志 func (r *SupervisorController) ClearLog(ctx http.Context) http.Response { if out, err := shell.Execf(`echo "" > /var/log/supervisor/supervisord.log`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Config 获取配置 @@ -66,10 +66,10 @@ func (r *SupervisorController) Config(ctx http.Context) http.Response { } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig 保存配置 @@ -83,14 +83,14 @@ func (r *SupervisorController) SaveConfig(ctx http.Context) http.Response { } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = systemctl.Restart(r.service); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重启 %s 服务失败", r.service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重启 %s 服务失败", r.service)) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // Processes 进程列表 @@ -104,7 +104,7 @@ func (r *SupervisorController) Processes(ctx http.Context) http.Response { out, err := shell.Execf(`supervisorctl status | awk '{print $1}'`) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } var processes []process @@ -130,9 +130,9 @@ func (r *SupervisorController) Processes(ctx http.Context) http.Response { processes = append(processes, p) } - paged, total := controllers.Paginate(ctx, processes) + paged, total := h.Paginate(ctx, processes) - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -142,30 +142,30 @@ func (r *SupervisorController) Processes(ctx http.Context) http.Response { func (r *SupervisorController) StartProcess(ctx http.Context) http.Response { process := ctx.Request().Input("process") if out, err := shell.Execf(`supervisorctl start %s`, process); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // StopProcess 停止进程 func (r *SupervisorController) StopProcess(ctx http.Context) http.Response { process := ctx.Request().Input("process") if out, err := shell.Execf(`supervisorctl stop %s`, process); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // RestartProcess 重启进程 func (r *SupervisorController) RestartProcess(ctx http.Context) http.Response { process := ctx.Request().Input("process") if out, err := shell.Execf(`supervisorctl restart %s`, process); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ProcessLog 进程日志 @@ -180,15 +180,15 @@ func (r *SupervisorController) ProcessLog(ctx http.Context) http.Response { } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "无法从进程"+process+"的配置文件中获取日志路径") + return h.Error(ctx, http.StatusInternalServerError, "无法从进程"+process+"的配置文件中获取日志路径") } log, err := shell.Execf(`tail -n 200 ` + logPath) if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, log) + return h.Error(ctx, http.StatusInternalServerError, log) } - return controllers.Success(ctx, log) + return h.Success(ctx, log) } // ClearProcessLog 清空进程日志 @@ -203,14 +203,14 @@ func (r *SupervisorController) ClearProcessLog(ctx http.Context) http.Response { } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("无法从进程%s的配置文件中获取日志路径", process)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("无法从进程%s的配置文件中获取日志路径", process)) } if out, err := shell.Execf(`echo "" > ` + logPath); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // ProcessConfig 获取进程配置 @@ -225,10 +225,10 @@ func (r *SupervisorController) ProcessConfig(ctx http.Context) http.Response { } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return controllers.Success(ctx, config) + return h.Success(ctx, config) } // SaveProcessConfig 保存进程配置 @@ -243,19 +243,19 @@ func (r *SupervisorController) SaveProcessConfig(ctx http.Context) http.Response } if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } _, _ = shell.Execf(`supervisorctl reread`) _, _ = shell.Execf(`supervisorctl update`) _, _ = shell.Execf(`supervisorctl restart %s`, process) - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // AddProcess 添加进程 func (r *SupervisorController) AddProcess(ctx http.Context) http.Response { - if sanitize := controllers.Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "name": "required|alpha_dash", "user": "required|alpha_dash", "path": "required", @@ -291,21 +291,21 @@ stdout_logfile_maxbytes=2MB } if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } _, _ = shell.Execf(`supervisorctl reread`) _, _ = shell.Execf(`supervisorctl update`) _, _ = shell.Execf(`supervisorctl start %s`, name) - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteProcess 删除进程 func (r *SupervisorController) DeleteProcess(ctx http.Context) http.Response { process := ctx.Request().Input("process") if out, err := shell.Execf(`supervisorctl stop %s`, process); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } var logPath string @@ -313,24 +313,24 @@ func (r *SupervisorController) DeleteProcess(ctx http.Context) http.Response { if os.IsRHEL() { logPath, err = shell.Execf(`cat '/etc/supervisord.d/%s.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`, process) if err := io.Remove(`/etc/supervisord.d/` + process + `.conf`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } else { logPath, err = shell.Execf(`cat '/etc/supervisor/conf.d/%s.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`, process) if err := io.Remove(`/etc/supervisor/conf.d/` + process + `.conf`); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "无法从进程"+process+"的配置文件中获取日志路径") + return h.Error(ctx, http.StatusInternalServerError, "无法从进程"+process+"的配置文件中获取日志路径") } if err := io.Remove(logPath); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } _, _ = shell.Execf(`supervisorctl reread`) _, _ = shell.Execf(`supervisorctl update`) - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/plugins/toolbox_controller.go b/app/http/controllers/plugins/toolbox_controller.go index b724b5ed..a6e079fc 100644 --- a/app/http/controllers/plugins/toolbox_controller.go +++ b/app/http/controllers/plugins/toolbox_controller.go @@ -7,7 +7,7 @@ import ( "github.com/goravel/framework/contracts/http" "github.com/spf13/cast" - "github.com/TheTNB/panel/v2/app/http/controllers" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -24,11 +24,11 @@ func NewToolBoxController() *ToolBoxController { func (r *ToolBoxController) GetDNS(ctx http.Context) http.Response { raw, err := io.Read("/etc/resolv.conf") if err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } match := regexp.MustCompile(`nameserver\s+(\S+)`).FindAllStringSubmatch(raw, -1) if len(match) == 0 { - return controllers.Error(ctx, http.StatusInternalServerError, "找不到 DNS 信息") + return h.Error(ctx, http.StatusInternalServerError, "找不到 DNS 信息") } var dns []string @@ -36,7 +36,7 @@ func (r *ToolBoxController) GetDNS(ctx http.Context) http.Response { dns = append(dns, m[1]) } - return controllers.Success(ctx, dns) + return h.Success(ctx, dns) } // SetDNS 设置 DNS 信息 @@ -45,7 +45,7 @@ func (r *ToolBoxController) SetDNS(ctx http.Context) http.Response { dns2 := ctx.Request().Input("dns2") if len(dns1) == 0 || len(dns2) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "DNS 信息不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "DNS 信息不能为空") } var dns string @@ -53,10 +53,10 @@ func (r *ToolBoxController) SetDNS(ctx http.Context) http.Response { dns += "nameserver " + dns2 + "\n" if err := io.Write("/etc/resolv.conf", dns, 0644); err != nil { - return controllers.Error(ctx, http.StatusInternalServerError, "写入 DNS 信息失败") + return h.Error(ctx, http.StatusInternalServerError, "写入 DNS 信息失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetSWAP 获取 SWAP 信息 @@ -66,7 +66,7 @@ func (r *ToolBoxController) GetSWAP(ctx http.Context) http.Response { if io.Exists("/www/swap") { file, err := io.FileInfo("/www/swap") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取 SWAP 信息失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取 SWAP 信息失败") } size = file.Size() / 1024 / 1024 @@ -78,7 +78,7 @@ func (r *ToolBoxController) GetSWAP(ctx http.Context) http.Response { raw, err := shell.Execf("free | grep Swap") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取 SWAP 信息失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取 SWAP 信息失败") } match := regexp.MustCompile(`Swap:\s+(\d+)\s+(\d+)\s+(\d+)`).FindStringSubmatch(raw) @@ -87,7 +87,7 @@ func (r *ToolBoxController) GetSWAP(ctx http.Context) http.Response { free = str.FormatBytes(cast.ToFloat64(match[3]) * 1024) } - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "size": size, "used": used, @@ -101,62 +101,62 @@ func (r *ToolBoxController) SetSWAP(ctx http.Context) http.Response { if io.Exists("/www/swap") { if out, err := shell.Execf("swapoff /www/swap"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } if out, err := shell.Execf("rm -f /www/swap"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } if out, err := shell.Execf("sed -i '/www\\/swap/d' /etc/fstab"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } } if size > 1 { free, err := shell.Execf("df -k /www | awk '{print $4}' | tail -n 1") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取磁盘空间失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取磁盘空间失败") } if cast.ToInt64(free)*1024 < int64(size)*1024*1024 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "磁盘空间不足,当前剩余 "+str.FormatBytes(cast.ToFloat64(free))) + return h.Error(ctx, http.StatusUnprocessableEntity, "磁盘空间不足,当前剩余 "+str.FormatBytes(cast.ToFloat64(free))) } btrfsCheck, _ := shell.Execf("df -T /www | awk '{print $2}' | tail -n 1") if strings.Contains(btrfsCheck, "btrfs") { if out, err := shell.Execf("btrfs filesystem mkswapfile --size " + cast.ToString(size) + "M --uuid clear /www/swap"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } } else { if out, err := shell.Execf("dd if=/dev/zero of=/www/swap bs=1M count=" + cast.ToString(size)); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } if out, err := shell.Execf("mkswap -f /www/swap"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } if err := io.Chmod("/www/swap", 0600); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "设置 SWAP 权限失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "设置 SWAP 权限失败") } } if out, err := shell.Execf("swapon /www/swap"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } if out, err := shell.Execf("echo '/www/swap swap swap defaults 0 0' >> /etc/fstab"); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetTimezone 获取时区 func (r *ToolBoxController) GetTimezone(ctx http.Context) http.Response { raw, err := shell.Execf("timedatectl | grep zone") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取时区信息失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取时区信息失败") } match := regexp.MustCompile(`zone:\s+(\S+)`).FindStringSubmatch(raw) if len(match) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到时区信息") + return h.Error(ctx, http.StatusUnprocessableEntity, "找不到时区信息") } type zone struct { @@ -166,7 +166,7 @@ func (r *ToolBoxController) GetTimezone(ctx http.Context) http.Response { zonesRaw, err := shell.Execf("timedatectl list-timezones") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取时区列表失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "获取时区列表失败") } zones := strings.Split(zonesRaw, "\n") @@ -178,7 +178,7 @@ func (r *ToolBoxController) GetTimezone(ctx http.Context) http.Response { }) } - return controllers.Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "timezone": match[1], "timezones": zonesList, }) @@ -188,54 +188,54 @@ func (r *ToolBoxController) GetTimezone(ctx http.Context) http.Response { func (r *ToolBoxController) SetTimezone(ctx http.Context) http.Response { timezone := ctx.Request().Input("timezone") if len(timezone) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "时区不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "时区不能为空") } if out, err := shell.Execf("timedatectl set-timezone %s", timezone); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // GetHosts 获取 hosts 信息 func (r *ToolBoxController) GetHosts(ctx http.Context) http.Response { hosts, err := io.Read("/etc/hosts") if err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error()) + return h.Error(ctx, http.StatusUnprocessableEntity, err.Error()) } - return controllers.Success(ctx, hosts) + return h.Success(ctx, hosts) } // SetHosts 设置 hosts 信息 func (r *ToolBoxController) SetHosts(ctx http.Context) http.Response { hosts := ctx.Request().Input("hosts") if len(hosts) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "hosts 信息不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "hosts 信息不能为空") } if err := io.Write("/etc/hosts", hosts, 0644); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "写入 hosts 信息失败") + return h.Error(ctx, http.StatusUnprocessableEntity, "写入 hosts 信息失败") } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } // SetRootPassword 设置 root 密码 func (r *ToolBoxController) SetRootPassword(ctx http.Context) http.Response { password := ctx.Request().Input("password") if len(password) == 0 { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "密码不能为空") + return h.Error(ctx, http.StatusUnprocessableEntity, "密码不能为空") } if !regexp.MustCompile(`^[a-zA-Z0-9·~!@#$%^&*()_+-=\[\]{};:'",./<>?]{6,20}$`).MatchString(password) { - return controllers.Error(ctx, http.StatusUnprocessableEntity, "密码必须为 6-20 位字母、数字或特殊字符") + return h.Error(ctx, http.StatusUnprocessableEntity, "密码必须为 6-20 位字母、数字或特殊字符") } password = strings.ReplaceAll(password, `'`, `\'`) if out, err := shell.Execf(`yes '` + password + `' | passwd root`); err != nil { - return controllers.Error(ctx, http.StatusUnprocessableEntity, out) + return h.Error(ctx, http.StatusUnprocessableEntity, out) } - return controllers.Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/safe_controller.go b/app/http/controllers/safe_controller.go index a26d7fde..39e4211f 100644 --- a/app/http/controllers/safe_controller.go +++ b/app/http/controllers/safe_controller.go @@ -7,6 +7,7 @@ import ( "github.com/goravel/framework/contracts/http" "github.com/spf13/cast" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -32,7 +33,7 @@ func NewSafeController() *SafeController { // GetFirewallStatus 获取防火墙状态 func (r *SafeController) GetFirewallStatus(ctx http.Context) http.Response { - return Success(ctx, r.firewallStatus()) + return h.Success(ctx, r.firewallStatus()) } // SetFirewallStatus 设置防火墙状态 @@ -71,28 +72,28 @@ func (r *SafeController) SetFirewallStatus(ctx http.Context) http.Response { } if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetFirewallRules 获取防火墙规则 func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response { if !r.firewallStatus() { - return Success(ctx, nil) + return h.Success(ctx, nil) } var rules []map[string]string if os.IsRHEL() { out, err := shell.Execf("firewall-cmd --list-all") if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } match := regexp.MustCompile(`ports: (.*)`).FindStringSubmatch(out) if len(match) == 0 { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []map[string]string{}, }) @@ -115,11 +116,11 @@ func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response { } else { out, err := shell.Execf("ufw status | grep -v '(v6)' | grep ALLOW | awk '{print $1}'") if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if len(out) == 0 { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": 0, "items": []map[string]string{}, }) @@ -140,9 +141,9 @@ func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response { } } - paged, total := Paginate(ctx, rules) + paged, total := h.Paginate(ctx, rules) - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -151,13 +152,13 @@ func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response { // AddFirewallRule 添加防火墙规则 func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response { if !r.firewallStatus() { - return Error(ctx, http.StatusInternalServerError, "防火墙未启动") + return h.Error(ctx, http.StatusInternalServerError, "防火墙未启动") } port := ctx.Request().Input("port") protocol := ctx.Request().Input("protocol") if port == "" || protocol == "" || (protocol != "tcp" && protocol != "udp") { - return Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } // 端口有 2 种写法,一种是 80-443,一种是 80 if strings.Contains(port, "-") { @@ -165,24 +166,24 @@ func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response { startPort := cast.ToInt(ports[0]) endPort := cast.ToInt(ports[1]) if startPort < 1 || startPort > 65535 || endPort < 1 || endPort > 65535 || startPort > endPort { - return Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } } else { port := cast.ToInt(port) if port < 1 || port > 65535 { - return Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } } if os.IsRHEL() { if out, err := shell.Execf("firewall-cmd --remove-port=%s/%s --permanent", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --add-port=%s/%s --permanent", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { // ufw 需要替换 - 为 : 添加 @@ -190,29 +191,29 @@ func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response { port = strings.ReplaceAll(port, "-", ":") } if out, err := shell.Execf("ufw delete allow %s/%s", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw allow %s/%s", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } - return Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteFirewallRule 删除防火墙规则 func (r *SafeController) DeleteFirewallRule(ctx http.Context) http.Response { if !r.firewallStatus() { - return Error(ctx, http.StatusUnprocessableEntity, "防火墙未启动") + return h.Error(ctx, http.StatusUnprocessableEntity, "防火墙未启动") } port := ctx.Request().Input("port") protocol := ctx.Request().Input("protocol") if port == "" || protocol == "" { - return Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } if protocol == "all" { protocol = "" @@ -222,21 +223,21 @@ func (r *SafeController) DeleteFirewallRule(ctx http.Context) http.Response { if os.IsRHEL() { if out, err := shell.Execf("firewall-cmd --remove-port=%s%s --permanent", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if out, err := shell.Execf("ufw delete allow %s%s", port, protocol); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } - return Success(ctx, nil) + return h.Success(ctx, nil) } // firewallStatus 获取防火墙状态 @@ -255,53 +256,53 @@ func (r *SafeController) firewallStatus() bool { func (r *SafeController) GetSshStatus(ctx http.Context) http.Response { running, err := systemctl.Status(r.ssh) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, running) + return h.Success(ctx, running) } // SetSshStatus 设置 SSH 状态 func (r *SafeController) SetSshStatus(ctx http.Context) http.Response { if ctx.Request().InputBool("status") { if err := systemctl.Enable(r.ssh); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Start(r.ssh); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } else { if err := systemctl.Stop(r.ssh); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := systemctl.Disable(r.ssh); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetSshPort 获取 SSH 端口 func (r *SafeController) GetSshPort(ctx http.Context) http.Response { out, err := shell.Execf("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'") if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return Success(ctx, cast.ToInt(out)) + return h.Success(ctx, cast.ToInt(out)) } // SetSshPort 设置 SSH 端口 func (r *SafeController) SetSshPort(ctx http.Context) http.Response { port := ctx.Request().InputInt("port", 0) if port == 0 { - return Error(ctx, http.StatusUnprocessableEntity, "参数错误") + return h.Error(ctx, http.StatusUnprocessableEntity, "参数错误") } oldPort, err := shell.Execf("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'") if err != nil { - return Error(ctx, http.StatusInternalServerError, oldPort) + return h.Error(ctx, http.StatusInternalServerError, oldPort) } _, _ = shell.Execf("sed -i 's/#Port %s/Port %d/g' /etc/ssh/sshd_config", oldPort, port) _, _ = shell.Execf("sed -i 's/Port %s/Port %d/g' /etc/ssh/sshd_config", oldPort, port) @@ -311,7 +312,7 @@ func (r *SafeController) SetSshPort(ctx http.Context) http.Response { _ = systemctl.Restart(r.ssh) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetPingStatus 获取 Ping 状态 @@ -319,23 +320,23 @@ func (r *SafeController) GetPingStatus(ctx http.Context) http.Response { if os.IsRHEL() { out, err := shell.Execf(`firewall-cmd --list-all`) if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if !strings.Contains(out, `rule protocol value="icmp" drop`) { - return Success(ctx, true) + return h.Success(ctx, true) } else { - return Success(ctx, false) + return h.Success(ctx, false) } } else { config, err := io.Read("/etc/ufw/before.rules") if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if strings.Contains(config, "-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT") { - return Success(ctx, true) + return h.Success(ctx, true) } else { - return Success(ctx, false) + return h.Success(ctx, false) } } } @@ -359,7 +360,7 @@ func (r *SafeController) SetPingStatus(ctx http.Context) http.Response { } if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if os.IsRHEL() { @@ -369,8 +370,8 @@ func (r *SafeController) SetPingStatus(ctx http.Context) http.Response { } if err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/setting_controller.go b/app/http/controllers/setting_controller.go index b29461e6..4d9f5d54 100644 --- a/app/http/controllers/setting_controller.go +++ b/app/http/controllers/setting_controller.go @@ -11,6 +11,7 @@ import ( "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" "github.com/TheTNB/panel/v2/pkg/cert" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" @@ -42,13 +43,13 @@ func (r *SettingController) List(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("获取面板设置列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } userID := cast.ToUint(ctx.Value("user_id")) var user models.User if err = facades.Orm().Query().Where("id", userID).Get(&user); err != nil { - return Error(ctx, http.StatusInternalServerError, "获取用户信息失败") + return h.Error(ctx, http.StatusInternalServerError, "获取用户信息失败") } port, err := shell.Execf(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`) @@ -56,10 +57,10 @@ func (r *SettingController) List(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("获取面板端口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "name": r.setting.Get(models.SettingKeyName), "language": facades.Config().GetString("app.locale"), "entrance": facades.Config().GetString("panel.entrance"), @@ -85,7 +86,7 @@ func (r *SettingController) List(ctx http.Context) http.Response { // @Router /panel/setting/update [post] func (r *SettingController) Update(ctx http.Context) http.Response { var updateRequest requests.Update - sanitize := SanitizeRequest(ctx, &updateRequest) + sanitize := h.SanitizeRequest(ctx, &updateRequest) if sanitize != nil { return sanitize } @@ -95,12 +96,12 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("保存面板名称失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if !io.Exists(updateRequest.BackupPath) { if err = io.Mkdir(updateRequest.BackupPath, 0644); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } } err = r.setting.Set(models.SettingKeyBackupPath, updateRequest.BackupPath) @@ -108,14 +109,14 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("保存备份目录失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if !io.Exists(updateRequest.WebsitePath) { if err = io.Mkdir(updateRequest.WebsitePath, 0755); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err = io.Chown(updateRequest.WebsitePath, "www", "www"); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } } err = r.setting.Set(models.SettingKeyWebsitePath, updateRequest.WebsitePath) @@ -123,13 +124,13 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("保存建站目录失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } userID := cast.ToUint(ctx.Value("user_id")) var user models.User if err = facades.Orm().Query().Where("id", userID).Get(&user); err != nil { - return Error(ctx, http.StatusInternalServerError, "获取用户信息失败") + return h.Error(ctx, http.StatusInternalServerError, "获取用户信息失败") } user.Username = updateRequest.UserName @@ -137,7 +138,7 @@ func (r *SettingController) Update(ctx http.Context) http.Response { if len(updateRequest.Password) > 0 { hash, err := facades.Hash().Make(updateRequest.Password) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } user.Password = hash } @@ -145,7 +146,7 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("保存用户信息失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } oldPort, err := shell.Execf(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`) @@ -153,33 +154,33 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("获取面板端口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } port := cast.ToString(updateRequest.Port) if oldPort != port { if out, err := shell.Execf("sed -i 's/APP_PORT=%s/APP_PORT=%s/g' /www/panel/panel.conf", oldPort, port); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if os.IsRHEL() { if out, err := shell.Execf("firewall-cmd --remove-port=%s/tcp --permanent", oldPort); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --add-port=%s/tcp --permanent", port); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("firewall-cmd --reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if out, err := shell.Execf("ufw delete allow %s/tcp", oldPort); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw allow %s/tcp", port); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } if out, err := shell.Execf("ufw reload"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } } @@ -189,12 +190,12 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("获取面板入口失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } entrance := cast.ToString(updateRequest.Entrance) if oldEntrance != entrance { if out, err := shell.Execf("sed -i 's!APP_ENTRANCE=" + oldEntrance + "!APP_ENTRANCE=" + entrance + "!g' /www/panel/panel.conf"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } @@ -203,11 +204,11 @@ func (r *SettingController) Update(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "面板设置").With(map[string]any{ "error": err.Error(), }).Info("获取面板语言失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if oldLanguage != updateRequest.Language { if out, err := shell.Execf("sed -i 's/APP_LOCALE=" + oldLanguage + "/APP_LOCALE=" + updateRequest.Language + "/g' /www/panel/panel.conf"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } @@ -215,7 +216,7 @@ func (r *SettingController) Update(ctx http.Context) http.Response { tools.RestartPanel() } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetHttps @@ -231,14 +232,14 @@ func (r *SettingController) GetHttps(ctx http.Context) http.Response { keyPath := facades.Config().GetString("http.tls.ssl.key") crt, err := io.Read(certPath) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } key, err := io.Read(keyPath) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "https": facades.Config().GetBool("panel.ssl"), "cert": crt, "key": key, @@ -257,33 +258,33 @@ func (r *SettingController) GetHttps(ctx http.Context) http.Response { // @Router /panel/setting/https [post] func (r *SettingController) UpdateHttps(ctx http.Context) http.Response { var httpsRequest requests.Https - sanitize := SanitizeRequest(ctx, &httpsRequest) + sanitize := h.SanitizeRequest(ctx, &httpsRequest) if sanitize != nil { return sanitize } if httpsRequest.Https { if _, err := cert.ParseCert(httpsRequest.Cert); err != nil { - return Error(ctx, http.StatusBadRequest, "证书格式错误") + return h.Error(ctx, http.StatusBadRequest, "证书格式错误") } if _, err := cert.ParseKey(httpsRequest.Key); err != nil { - return Error(ctx, http.StatusBadRequest, "密钥格式错误") + return h.Error(ctx, http.StatusBadRequest, "密钥格式错误") } if err := io.Write(path.Executable("storage/ssl.crt"), httpsRequest.Cert, 0700); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := io.Write(path.Executable("storage/ssl.key"), httpsRequest.Key, 0700); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if out, err := shell.Execf("sed -i 's/APP_SSL=false/APP_SSL=true/g' /www/panel/panel.conf"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } else { if out, err := shell.Execf("sed -i 's/APP_SSL=true/APP_SSL=false/g' /www/panel/panel.conf"); err != nil { - return Error(ctx, http.StatusInternalServerError, out) + return h.Error(ctx, http.StatusInternalServerError, out) } } tools.RestartPanel() - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/ssh_controller.go b/app/http/controllers/ssh_controller.go index 7be31ff9..06122147 100644 --- a/app/http/controllers/ssh_controller.go +++ b/app/http/controllers/ssh_controller.go @@ -15,6 +15,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/ssh" ) @@ -37,10 +38,10 @@ func (r *SshController) GetInfo(ctx http.Context) http.Response { user := r.setting.Get(models.SettingKeySshUser) password := r.setting.Get(models.SettingKeySshPassword) if len(host) == 0 || len(user) == 0 || len(password) == 0 { - return Error(ctx, http.StatusInternalServerError, "SSH 配置不完整") + return h.Error(ctx, http.StatusInternalServerError, "SSH 配置不完整") } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "host": host, "port": cast.ToInt(port), "user": user, @@ -50,7 +51,7 @@ func (r *SshController) GetInfo(ctx http.Context) http.Response { // UpdateInfo 更新 SSH 配置 func (r *SshController) UpdateInfo(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "host": "required", "port": "required", "user": "required", @@ -64,19 +65,19 @@ func (r *SshController) UpdateInfo(ctx http.Context) http.Response { user := ctx.Request().Input("user") password := ctx.Request().Input("password") if err := r.setting.Set(models.SettingKeySshHost, host); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := r.setting.Set(models.SettingKeySshPort, port); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := r.setting.Set(models.SettingKeySshUser, user); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := r.setting.Set(models.SettingKeySshPassword, password); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Session SSH 会话 @@ -95,7 +96,7 @@ func (r *SshController) Session(ctx http.Context) http.Response { facades.Log().Tags("面板", "SSH").With(map[string]any{ "error": err.Error(), }).Infof("建立连接失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } defer ws.Close() @@ -109,7 +110,7 @@ func (r *SshController) Session(ctx http.Context) http.Response { if err != nil { _ = ws.WriteControl(websocket.CloseMessage, []byte(err.Error()), time.Now().Add(time.Second)) - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } defer client.Close() @@ -117,7 +118,7 @@ func (r *SshController) Session(ctx http.Context) http.Response { if err != nil { _ = ws.WriteControl(websocket.CloseMessage, []byte(err.Error()), time.Now().Add(time.Second)) - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } defer turn.Close() diff --git a/app/http/controllers/system_controller.go b/app/http/controllers/system_controller.go index 34596594..61dbe95c 100644 --- a/app/http/controllers/system_controller.go +++ b/app/http/controllers/system_controller.go @@ -5,6 +5,7 @@ import ( "github.com/goravel/framework/contracts/http" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/systemctl" ) @@ -25,7 +26,7 @@ func NewSystemController() *SystemController { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/status [get] func (r *SystemController) ServiceStatus(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -34,10 +35,10 @@ func (r *SystemController) ServiceStatus(ctx http.Context) http.Response { service := ctx.Request().Query("service") status, err := systemctl.Status(service) if err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("获取 %s 服务运行状态失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("获取 %s 服务运行状态失败", service)) } - return Success(ctx, status) + return h.Success(ctx, status) } // ServiceIsEnabled @@ -50,7 +51,7 @@ func (r *SystemController) ServiceStatus(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/isEnabled [get] func (r *SystemController) ServiceIsEnabled(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -59,10 +60,10 @@ func (r *SystemController) ServiceIsEnabled(ctx http.Context) http.Response { service := ctx.Request().Query("service") enabled, err := systemctl.IsEnabled(service) if err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("获取 %s 服务启用状态失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("获取 %s 服务启用状态失败", service)) } - return Success(ctx, enabled) + return h.Success(ctx, enabled) } // ServiceEnable @@ -75,7 +76,7 @@ func (r *SystemController) ServiceIsEnabled(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/enable [post] func (r *SystemController) ServiceEnable(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -83,10 +84,10 @@ func (r *SystemController) ServiceEnable(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Enable(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("启用 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("启用 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ServiceDisable @@ -99,7 +100,7 @@ func (r *SystemController) ServiceEnable(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/disable [post] func (r *SystemController) ServiceDisable(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -107,10 +108,10 @@ func (r *SystemController) ServiceDisable(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Disable(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("禁用 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("禁用 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ServiceRestart @@ -123,7 +124,7 @@ func (r *SystemController) ServiceDisable(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/restart [post] func (r *SystemController) ServiceRestart(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -131,10 +132,10 @@ func (r *SystemController) ServiceRestart(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Restart(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重启 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重启 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ServiceReload @@ -147,7 +148,7 @@ func (r *SystemController) ServiceRestart(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/reload [post] func (r *SystemController) ServiceReload(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -155,10 +156,10 @@ func (r *SystemController) ServiceReload(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Reload(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ServiceStart @@ -171,7 +172,7 @@ func (r *SystemController) ServiceReload(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/start [post] func (r *SystemController) ServiceStart(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -179,10 +180,10 @@ func (r *SystemController) ServiceStart(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Start(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("启动 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("启动 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ServiceStop @@ -195,7 +196,7 @@ func (r *SystemController) ServiceStart(ctx http.Context) http.Response { // @Success 200 {object} controllers.SuccessResponse // @Router /panel/system/service/stop [post] func (r *SystemController) ServiceStop(ctx http.Context) http.Response { - if sanitize := Sanitize(ctx, map[string]string{ + if sanitize := h.Sanitize(ctx, map[string]string{ "service": "required|string", }); sanitize != nil { return sanitize @@ -203,8 +204,8 @@ func (r *SystemController) ServiceStop(ctx http.Context) http.Response { service := ctx.Request().Input("service") if err := systemctl.Stop(service); err != nil { - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("停止 %s 服务失败", service)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("停止 %s 服务失败", service)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/task_controller.go b/app/http/controllers/task_controller.go index c989b598..6974f837 100644 --- a/app/http/controllers/task_controller.go +++ b/app/http/controllers/task_controller.go @@ -5,6 +5,7 @@ import ( "github.com/goravel/framework/facades" "github.com/TheTNB/panel/v2/app/models" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/shell" ) @@ -23,12 +24,12 @@ func (r *TaskController) Status(ctx http.Context) http.Response { var task models.Task err := facades.Orm().Query().Where("status", models.TaskStatusWaiting).OrWhere("status", models.TaskStatusRunning).FirstOrFail(&task) if err == nil { - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "task": true, }) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "task": false, }) } @@ -42,10 +43,10 @@ func (r *TaskController) List(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "任务中心").With(map[string]any{ "error": err.Error(), }).Info("查询任务列表失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": tasks, }) @@ -60,15 +61,15 @@ func (r *TaskController) Log(ctx http.Context) http.Response { "id": ctx.Request().QueryInt("id"), "error": err.Error(), }).Info("查询任务失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } log, err := shell.Execf(`tail -n 500 '` + task.Log + `'`) if err != nil { - return Error(ctx, http.StatusInternalServerError, "日志已被清理") + return h.Error(ctx, http.StatusInternalServerError, "日志已被清理") } - return Success(ctx, log) + return h.Success(ctx, log) } // Delete 删除任务 @@ -80,8 +81,8 @@ func (r *TaskController) Delete(ctx http.Context) http.Response { "id": ctx.Request().QueryInt("id"), "error": err.Error(), }).Info("删除任务失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/app/http/controllers/user_controller.go b/app/http/controllers/user_controller.go index 219b7636..d9a6830a 100644 --- a/app/http/controllers/user_controller.go +++ b/app/http/controllers/user_controller.go @@ -7,6 +7,7 @@ import ( "github.com/TheTNB/panel/v2/app/http/requests/user" "github.com/TheTNB/panel/v2/app/models" + "github.com/TheTNB/panel/v2/pkg/h" ) type UserController struct { @@ -32,7 +33,7 @@ func NewUserController() *UserController { // @Router /panel/user/login [post] func (r *UserController) Login(ctx http.Context) http.Response { var loginRequest requests.Login - sanitize := SanitizeRequest(ctx, &loginRequest) + sanitize := h.SanitizeRequest(ctx, &loginRequest) if sanitize != nil { return sanitize } @@ -43,11 +44,11 @@ func (r *UserController) Login(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "用户").With(map[string]any{ "error": err.Error(), }).Info("查询用户失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if user.ID == 0 || !facades.Hash().Check(loginRequest.Password, user.Password) { - return Error(ctx, http.StatusForbidden, "用户名或密码错误") + return h.Error(ctx, http.StatusForbidden, "用户名或密码错误") } if facades.Hash().NeedsRehash(user.Password) { @@ -56,12 +57,12 @@ func (r *UserController) Login(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "用户").With(map[string]any{ "error": err.Error(), }).Info("更新密码失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } } ctx.Request().Session().Put("user_id", user.ID) - return Success(ctx, nil) + return h.Success(ctx, nil) } // Logout @@ -77,7 +78,7 @@ func (r *UserController) Logout(ctx http.Context) http.Response { ctx.Request().Session().Forget("user_id") } - return Success(ctx, nil) + return h.Success(ctx, nil) } // IsLogin @@ -89,10 +90,10 @@ func (r *UserController) Logout(ctx http.Context) http.Response { // @Router /panel/user/isLogin [get] func (r *UserController) IsLogin(ctx http.Context) http.Response { if !ctx.Request().HasSession() { - return Success(ctx, false) + return h.Success(ctx, false) } - return Success(ctx, ctx.Request().Session().Has("user_id")) + return h.Success(ctx, ctx.Request().Session().Has("user_id")) } // Info @@ -110,10 +111,10 @@ func (r *UserController) Info(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "用户").With(map[string]any{ "error": err.Error(), }).Info("获取用户信息失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "id": user.ID, "role": []string{"admin"}, "username": user.Username, diff --git a/app/http/controllers/website_controller.go b/app/http/controllers/website_controller.go index e118bd34..6bfb8e45 100644 --- a/app/http/controllers/website_controller.go +++ b/app/http/controllers/website_controller.go @@ -13,6 +13,7 @@ import ( "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/internal/services" + "github.com/TheTNB/panel/v2/pkg/h" "github.com/TheTNB/panel/v2/pkg/io" "github.com/TheTNB/panel/v2/pkg/shell" "github.com/TheTNB/panel/v2/pkg/str" @@ -44,7 +45,7 @@ func NewWebsiteController() *WebsiteController { // @Router /panel/websites [get] func (r *WebsiteController) List(ctx http.Context) http.Response { var paginateRequest commonrequests.Paginate - sanitize := SanitizeRequest(ctx, &paginateRequest) + sanitize := h.SanitizeRequest(ctx, &paginateRequest) if sanitize != nil { return sanitize } @@ -54,10 +55,10 @@ func (r *WebsiteController) List(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("获取网站列表失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": websites, }) @@ -75,7 +76,7 @@ func (r *WebsiteController) List(ctx http.Context) http.Response { // @Router /panel/websites [post] func (r *WebsiteController) Add(ctx http.Context) http.Response { var addRequest requests.Add - sanitize := SanitizeRequest(ctx, &addRequest) + sanitize := h.SanitizeRequest(ctx, &addRequest) if sanitize != nil { return sanitize } @@ -89,10 +90,10 @@ func (r *WebsiteController) Add(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("添加网站失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Delete @@ -107,7 +108,7 @@ func (r *WebsiteController) Add(ctx http.Context) http.Response { // @Router /panel/websites/delete [post] func (r *WebsiteController) Delete(ctx http.Context) http.Response { var deleteRequest requests.Delete - sanitize := SanitizeRequest(ctx, &deleteRequest) + sanitize := h.SanitizeRequest(ctx, &deleteRequest) if sanitize != nil { return sanitize } @@ -117,10 +118,10 @@ func (r *WebsiteController) Delete(ctx http.Context) http.Response { "id": deleteRequest.ID, "error": err.Error(), }).Info("删除网站失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetDefaultConfig @@ -134,14 +135,14 @@ func (r *WebsiteController) Delete(ctx http.Context) http.Response { func (r *WebsiteController) GetDefaultConfig(ctx http.Context) http.Response { index, err := io.Read("/www/server/openresty/html/index.html") if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } stop, err := io.Read("/www/server/openresty/html/stop.html") if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "index": index, "stop": stop, }) @@ -165,17 +166,17 @@ func (r *WebsiteController) SaveDefaultConfig(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("保存默认首页配置失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err := io.Write("/www/server/openresty/html/stop.html", stop, 0644); err != nil { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("保存默认停止页配置失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // GetConfig @@ -190,7 +191,7 @@ func (r *WebsiteController) SaveDefaultConfig(ctx http.Context) http.Response { // @Router /panel/websites/{id}/config [get] func (r *WebsiteController) GetConfig(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } @@ -201,10 +202,10 @@ func (r *WebsiteController) GetConfig(ctx http.Context) http.Response { "id": idRequest.ID, "error": err.Error(), }).Info("获取网站配置失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, config) + return h.Success(ctx, config) } // SaveConfig @@ -220,17 +221,17 @@ func (r *WebsiteController) GetConfig(ctx http.Context) http.Response { // @Router /panel/websites/{id}/config [post] func (r *WebsiteController) SaveConfig(ctx http.Context) http.Response { var saveConfigRequest requests.SaveConfig - sanitize := SanitizeRequest(ctx, &saveConfigRequest) + sanitize := h.SanitizeRequest(ctx, &saveConfigRequest) if sanitize != nil { return sanitize } err := r.website.SaveConfig(saveConfigRequest) if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ClearLog @@ -245,7 +246,7 @@ func (r *WebsiteController) SaveConfig(ctx http.Context) http.Response { // @Router /panel/websites/{id}/log [delete] func (r *WebsiteController) ClearLog(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } @@ -253,14 +254,14 @@ func (r *WebsiteController) ClearLog(ctx http.Context) http.Response { website := models.Website{} err := facades.Orm().Query().Where("id", idRequest.ID).Get(&website) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := io.Remove("/www/wwwlogs/" + website.Name + ".log"); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // UpdateRemark @@ -275,7 +276,7 @@ func (r *WebsiteController) ClearLog(ctx http.Context) http.Response { // @Router /panel/websites/{id}/updateRemark [post] func (r *WebsiteController) UpdateRemark(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } @@ -283,7 +284,7 @@ func (r *WebsiteController) UpdateRemark(ctx http.Context) http.Response { website := models.Website{} err := facades.Orm().Query().Where("id", idRequest.ID).Get(&website) if err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } website.Remark = ctx.Request().Input("remark") @@ -292,10 +293,10 @@ func (r *WebsiteController) UpdateRemark(ctx http.Context) http.Response { "id": idRequest.ID, "error": err.Error(), }).Info("更新网站备注失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // BackupList @@ -309,7 +310,7 @@ func (r *WebsiteController) UpdateRemark(ctx http.Context) http.Response { // @Router /panel/website/backupList [get] func (r *WebsiteController) BackupList(ctx http.Context) http.Response { var paginateRequest commonrequests.Paginate - sanitize := SanitizeRequest(ctx, &paginateRequest) + sanitize := h.SanitizeRequest(ctx, &paginateRequest) if sanitize != nil { return sanitize } @@ -319,12 +320,12 @@ func (r *WebsiteController) BackupList(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("获取备份列表失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - paged, total := Paginate(ctx, backups) + paged, total := h.Paginate(ctx, backups) - return Success(ctx, http.Json{ + return h.Success(ctx, http.Json{ "total": total, "items": paged, }) @@ -342,7 +343,7 @@ func (r *WebsiteController) BackupList(ctx http.Context) http.Response { // @Router /panel/websites/{id}/createBackup [post] func (r *WebsiteController) CreateBackup(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } @@ -353,7 +354,7 @@ func (r *WebsiteController) CreateBackup(ctx http.Context) http.Response { "id": idRequest.ID, "error": err.Error(), }).Info("获取网站信息失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := r.backup.WebSiteBackup(website); err != nil { @@ -361,10 +362,10 @@ func (r *WebsiteController) CreateBackup(ctx http.Context) http.Response { "id": idRequest.ID, "error": err.Error(), }).Info("备份网站失败") - return Error(ctx, http.StatusInternalServerError, "备份网站失败: "+err.Error()) + return h.Error(ctx, http.StatusInternalServerError, "备份网站失败: "+err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // UploadBackup @@ -380,7 +381,7 @@ func (r *WebsiteController) CreateBackup(ctx http.Context) http.Response { func (r *WebsiteController) UploadBackup(ctx http.Context) http.Response { file, err := ctx.Request().File("file") if err != nil { - return Error(ctx, http.StatusInternalServerError, "上传文件失败") + return h.Error(ctx, http.StatusInternalServerError, "上传文件失败") } backupPath := r.setting.Get(models.SettingKeyBackupPath) + "/website" @@ -396,10 +397,10 @@ func (r *WebsiteController) UploadBackup(ctx http.Context) http.Response { facades.Log().Request(ctx.Request()).Tags("面板", "网站管理").With(map[string]any{ "error": err.Error(), }).Info("上传备份失败") - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // RestoreBackup @@ -414,14 +415,14 @@ func (r *WebsiteController) UploadBackup(ctx http.Context) http.Response { // @Router /panel/websites/{id}/restoreBackup [post] func (r *WebsiteController) RestoreBackup(ctx http.Context) http.Response { var restoreBackupRequest requests.RestoreBackup - sanitize := SanitizeRequest(ctx, &restoreBackupRequest) + sanitize := h.SanitizeRequest(ctx, &restoreBackupRequest) if sanitize != nil { return sanitize } website := models.Website{} if err := facades.Orm().Query().Where("id", restoreBackupRequest.ID).Get(&website); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } if err := r.backup.WebsiteRestore(website, restoreBackupRequest.Name); err != nil { @@ -430,10 +431,10 @@ func (r *WebsiteController) RestoreBackup(ctx http.Context) http.Response { "file": restoreBackupRequest.Name, "error": err.Error(), }).Info("还原网站失败") - return Error(ctx, http.StatusInternalServerError, "还原网站失败: "+err.Error()) + return h.Error(ctx, http.StatusInternalServerError, "还原网站失败: "+err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // DeleteBackup @@ -448,7 +449,7 @@ func (r *WebsiteController) RestoreBackup(ctx http.Context) http.Response { // @Router /panel/website/deleteBackup [delete] func (r *WebsiteController) DeleteBackup(ctx http.Context) http.Response { var deleteBackupRequest requests.DeleteBackup - sanitize := SanitizeRequest(ctx, &deleteBackupRequest) + sanitize := h.SanitizeRequest(ctx, &deleteBackupRequest) if sanitize != nil { return sanitize } @@ -461,10 +462,10 @@ func (r *WebsiteController) DeleteBackup(ctx http.Context) http.Response { } if err := io.Remove(backupPath + "/" + deleteBackupRequest.Name); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // ResetConfig @@ -479,14 +480,14 @@ func (r *WebsiteController) DeleteBackup(ctx http.Context) http.Response { // @Router /panel/websites/{id}/resetConfig [post] func (r *WebsiteController) ResetConfig(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } website := models.Website{} if err := facades.Orm().Query().Where("id", idRequest.ID).Get(&website); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } website.Status = true @@ -496,7 +497,7 @@ func (r *WebsiteController) ResetConfig(ctx http.Context) http.Response { "id": idRequest.ID, "error": err.Error(), }).Info("保存网站配置失败") - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } raw := fmt.Sprintf(` @@ -571,10 +572,10 @@ server } if err := systemctl.Reload("openresty"); err != nil { _, err = shell.Execf("openresty -t") - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } // Status @@ -589,24 +590,24 @@ server // @Router /panel/websites/{id}/status [post] func (r *WebsiteController) Status(ctx http.Context) http.Response { var idRequest requests.ID - sanitize := SanitizeRequest(ctx, &idRequest) + sanitize := h.SanitizeRequest(ctx, &idRequest) if sanitize != nil { return sanitize } website := models.Website{} if err := facades.Orm().Query().Where("id", idRequest.ID).Get(&website); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } website.Status = ctx.Request().InputBool("status") if err := facades.Orm().Query().Save(&website); err != nil { - return ErrorSystem(ctx) + return h.ErrorSystem(ctx) } raw, err := io.Read("/www/server/vhost/" + website.Name + ".conf") if err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } // 运行目录 @@ -634,12 +635,12 @@ func (r *WebsiteController) Status(ctx http.Context) http.Response { } if err = io.Write("/www/server/vhost/"+website.Name+".conf", raw, 0644); err != nil { - return Error(ctx, http.StatusInternalServerError, err.Error()) + return h.Error(ctx, http.StatusInternalServerError, err.Error()) } if err = systemctl.Reload("openresty"); err != nil { _, err = shell.Execf("openresty -t") - return Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) + return h.Error(ctx, http.StatusInternalServerError, fmt.Sprintf("重载OpenResty失败: %v", err)) } - return Success(ctx, nil) + return h.Success(ctx, nil) } diff --git a/internal/services/cron.go b/internal/services/cron.go index 4a3d509a..4233a0a4 100644 --- a/internal/services/cron.go +++ b/internal/services/cron.go @@ -2,6 +2,7 @@ package services import ( "errors" + "github.com/TheTNB/panel/v2/app/models" "github.com/TheTNB/panel/v2/pkg/os" "github.com/TheTNB/panel/v2/pkg/shell" diff --git a/internal/services/website.go b/internal/services/website.go index 96aa52ab..dfa2d43d 100644 --- a/internal/services/website.go +++ b/internal/services/website.go @@ -4,7 +4,6 @@ package services import ( "errors" "fmt" - "github.com/TheTNB/panel/v2/embed" "path/filepath" "regexp" "slices" @@ -16,6 +15,7 @@ import ( requests "github.com/TheTNB/panel/v2/app/http/requests/website" "github.com/TheTNB/panel/v2/app/models" + "github.com/TheTNB/panel/v2/embed" "github.com/TheTNB/panel/v2/internal" "github.com/TheTNB/panel/v2/pkg/cert" "github.com/TheTNB/panel/v2/pkg/db" diff --git a/pkg/h/request.go b/pkg/h/request.go new file mode 100644 index 00000000..b321d6bc --- /dev/null +++ b/pkg/h/request.go @@ -0,0 +1,29 @@ +package h + +import "github.com/goravel/framework/contracts/http" + +// SanitizeRequest 消毒请求参数 +func SanitizeRequest(ctx http.Context, request http.FormRequest) http.Response { + errors, err := ctx.Request().ValidateRequest(request) + if err != nil { + return Error(ctx, http.StatusUnprocessableEntity, err.Error()) + } + if errors != nil { + return Error(ctx, http.StatusUnprocessableEntity, errors.One()) + } + + return nil +} + +// Sanitize 消毒参数 +func Sanitize(ctx http.Context, rules map[string]string) http.Response { + validator, err := ctx.Request().Validate(rules) + if err != nil { + return Error(ctx, http.StatusUnprocessableEntity, err.Error()) + } + if validator.Fails() { + return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One()) + } + + return nil +} diff --git a/app/http/controllers/controller.go b/pkg/h/response.go similarity index 64% rename from app/http/controllers/controller.go rename to pkg/h/response.go index e8d973fa..5a2c8b90 100644 --- a/app/http/controllers/controller.go +++ b/pkg/h/response.go @@ -1,10 +1,10 @@ -package controllers +package h import ( "github.com/goravel/framework/contracts/http" "github.com/goravel/framework/facades" - commonrequests "github.com/TheTNB/panel/v2/app/http/requests/common" + "github.com/TheTNB/panel/v2/app/http/requests/common" ) // SuccessResponse 通用成功响应 @@ -40,6 +40,7 @@ func ErrorSystem(ctx http.Context) http.Response { }) } +// Paginate 取分页条目 func Paginate[T any](ctx http.Context, allItems []T) (pagedItems []T, total int) { var paginateRequest commonrequests.Paginate sanitize := SanitizeRequest(ctx, &paginateRequest) @@ -65,29 +66,3 @@ func Paginate[T any](ctx http.Context, allItems []T) (pagedItems []T, total int) return allItems[startIndex:endIndex], total } - -// SanitizeRequest 消毒请求参数 -func SanitizeRequest(ctx http.Context, request http.FormRequest) http.Response { - errors, err := ctx.Request().ValidateRequest(request) - if err != nil { - return Error(ctx, http.StatusUnprocessableEntity, err.Error()) - } - if errors != nil { - return Error(ctx, http.StatusUnprocessableEntity, errors.One()) - } - - return nil -} - -// Sanitize 消毒参数 -func Sanitize(ctx http.Context, rules map[string]string) http.Response { - validator, err := ctx.Request().Validate(rules) - if err != nil { - return Error(ctx, http.StatusUnprocessableEntity, err.Error()) - } - if validator.Fails() { - return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One()) - } - - return nil -} diff --git a/routes/plugin.go b/routes/plugin.go index d66d6b57..2ef1a6f3 100644 --- a/routes/plugin.go +++ b/routes/plugin.go @@ -11,14 +11,6 @@ import ( // Plugin 加载插件路由 func Plugin() { facades.Route().Prefix("api/plugins").Middleware(middleware.Session(), middleware.MustInstall()).Group(func(r route.Router) { - r.Prefix("openresty").Group(func(route route.Router) { - openRestyController := plugins.NewOpenrestyController() - route.Get("load", openRestyController.Load) - route.Get("config", openRestyController.GetConfig) - route.Post("config", openRestyController.SaveConfig) - route.Get("errorLog", openRestyController.ErrorLog) - route.Post("clearErrorLog", openRestyController.ClearErrorLog) - }) r.Prefix("mysql").Group(func(route route.Router) { mySQLController := plugins.NewMySQLController() route.Get("load", mySQLController.Load)