From f2cfe0de0eeec8bc7abf9d754b9e89681743ecff Mon Sep 17 00:00:00 2001 From: Shulhan Date: Mon, 5 Feb 2024 03:21:53 +0700 Subject: all: implement form input file The FormInput now can be set to FormInputKindFile that will rendered as "" on the web user interface. Once submitted, the file name, type, size, and lastModification will be stored under FormInput Filename, Filetype, Filesize, and Filemodms. Implements: https://todo.sr.ht/~shulhan/trunks/1 --- example/example.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'example') diff --git a/example/example.go b/example/example.go index 17e24eb..27b5209 100644 --- a/example/example.go +++ b/example/example.go @@ -34,6 +34,7 @@ const ( pathExample = `/example` pathExampleError = `/example/error` pathExampleNamePage = `/example/:name/page` + pathExampleUpload = `/example/upload` ) const ( @@ -168,6 +169,14 @@ func (ex *Example) registerEndpoints() (err error) { Call: ex.pathExamplePost, }) + err = ex.trunks.Httpd.RegisterEndpoint(&libhttp.Endpoint{ + Method: libhttp.RequestMethodPost, + Path: pathExampleUpload, + RequestType: libhttp.RequestTypeMultipartForm, + ResponseType: libhttp.ResponseTypeJSON, + Call: ex.pathExampleUpload, + }) + return err } @@ -322,6 +331,30 @@ func (ex *Example) registerTargetHTTP() (err error) { Value: `123`, }, }, + }, { + Name: `HTTP upload`, + Hint: `Test uploading file`, + Method: libhttp.RequestMethodPost, + Path: pathExampleUpload, + RequestType: libhttp.RequestTypeMultipartForm, + Params: trunks.KeyFormInput{ + `file`: trunks.FormInput{ + Label: `File`, + Hint: `File to be uploaded.`, + Kind: trunks.FormInputKindFile, + FormDataName: func(key string) string { + if key == trunks.FormDataFilename { + return `name` + } + return key + }, + }, + `agree`: trunks.FormInput{ + Label: `Agree`, + Hint: `Additional parameter along file.`, + Kind: trunks.FormInputKindBoolean, + }, + }, }}, } @@ -431,6 +464,22 @@ func (ex *Example) pathExamplePost(epr *libhttp.EndpointRequest) (resb []byte, e return json.Marshal(&res) } +func (ex *Example) pathExampleUpload(epr *libhttp.EndpointRequest) (resb []byte, err error) { + var logp = `pathExampleUpload` + + var res = libhttp.EndpointResponse{} + + res.Code = http.StatusOK + res.Data = epr.HttpRequest.MultipartForm.Value + + resb, err = json.Marshal(res) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + return resb, nil +} + func (ex *Example) runExampleGet(req *trunks.RunRequest) (res *trunks.RunResponse, err error) { if req.Target.HTTPClient == nil { var httpcOpts = &libhttp.ClientOptions{ -- cgit v1.3