From d0b49dea8a4a85dcdddc5a246cc7b962d6d5cde1 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Mon, 23 Aug 2021 00:46:19 +0700 Subject: all: implement HTTP API and function to Save file on web-user interface The web-user interface now have button "Save" that save the edited content of file to storage. --- http_api.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'http_api.go') diff --git a/http_api.go b/http_api.go index 0a368c9..a200653 100644 --- a/http_api.go +++ b/http_api.go @@ -22,6 +22,12 @@ const ( paramNamePath = "path" ) +type fsRequest struct { + Path string `json:"path"` + Content []byte `json:"content"` + IsDir bool `json:"is_dir"` +} + func (aww *Awwan) registerHttpApis() (err error) { logp := "registerHttpApis" @@ -36,6 +42,17 @@ func (aww *Awwan) registerHttpApis() (err error) { return fmt.Errorf("%s: %w", logp, err) } + err = aww.httpd.RegisterEndpoint(&libhttp.Endpoint{ + Method: libhttp.RequestMethodPut, + Path: httpApiFs, + RequestType: libhttp.RequestTypeJSON, + ResponseType: libhttp.ResponseTypeJSON, + Call: aww.httpApiFsPut, + }) + if err != nil { + return fmt.Errorf("%s: %w", logp, err) + } + err = aww.httpd.RegisterEndpoint(&libhttp.Endpoint{ Method: libhttp.RequestMethodPost, Path: httpApiExecute, @@ -74,6 +91,43 @@ func (aww *Awwan) httpApiFs(epr *libhttp.EndpointRequest) ([]byte, error) { return json.Marshal(res) } +// +// httpApiFsPut save the content of file. +// +func (aww *Awwan) httpApiFsPut(epr *libhttp.EndpointRequest) (rawBody []byte, err error) { + var ( + logp = "httpApiFsPut" + res = &libhttp.EndpointResponse{} + req = &fsRequest{} + ) + + res.Code = http.StatusInternalServerError + + err = json.Unmarshal(epr.RequestBody, req) + if err != nil { + res.Message = fmt.Sprintf("%s: %s", logp, err) + return nil, res + } + + node := aww.memfsBase.PathNodes.Get(req.Path) + if node == nil { + res.Code = http.StatusNotFound + res.Message = fmt.Sprintf("%s: invalid or empty path %s", logp, req.Path) + return nil, res + } + + err = node.Save(req.Content) + if err != nil { + res.Message = fmt.Sprintf("%s: %s", logp, err) + return nil, res + } + + res.Code = http.StatusOK + res.Data = node + + return json.Marshal(res) +} + func (aww *Awwan) httpApiExecute(epr *libhttp.EndpointRequest) ([]byte, error) { var ( logp = "httpApiExecute" -- cgit v1.3-5-g45d5