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 --- httpd_dummy_test.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 httpd_dummy_test.go (limited to 'httpd_dummy_test.go') diff --git a/httpd_dummy_test.go b/httpd_dummy_test.go new file mode 100644 index 0000000..2902e3e --- /dev/null +++ b/httpd_dummy_test.go @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2024 M. Shulhan +// SPDX-License-Identifier: GPL-3.0-or-later + +package trunks + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" + + libhttp "github.com/shuLhan/share/lib/http" + libnet "github.com/shuLhan/share/lib/net" +) + +const ( + pathUpload = `/upload` +) + +var dummyEndpointUpload = libhttp.Endpoint{ + Method: libhttp.RequestMethodPost, + Path: pathUpload, + RequestType: libhttp.RequestTypeMultipartForm, + ResponseType: libhttp.ResponseTypeJSON, +} + +// httpdDummy dummy HTTP server as target for testing. +type httpdDummy struct { + *libhttp.Server +} + +// newHttpdDummy create and run dummy HTTP server. +func newHttpdDummy() (dum *httpdDummy, err error) { + var logp = `newHttpdDummy` + + var serverOpts = libhttp.ServerOptions{ + Address: `127.0.0.1:22796`, + } + + dum = &httpdDummy{} + + dum.Server, err = libhttp.NewServer(&serverOpts) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + err = dum.registerEndpoints() + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + go func() { + var errStart = dum.Server.Start() + if errStart != nil { + log.Fatalf(`%s: %s`, logp, errStart) + } + }() + + err = libnet.WaitAlive(`tcp`, serverOpts.Address, time.Second) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + return dum, nil +} + +func (dum *httpdDummy) registerEndpoints() (err error) { + var logp = `registerEndpoints` + + dummyEndpointUpload.Call = dum.upload + + err = dum.Server.RegisterEndpoint(&dummyEndpointUpload) + if err != nil { + return fmt.Errorf(`%s %s: %w`, logp, dummyEndpointUpload.Path, err) + } + + return nil +} + +// upload handle HTTP POST with request type "multipart/form-data". +// It will response by echoing back the [HttpRequest.MultipartForm] as JSON. +func (dum *httpdDummy) upload(epr *libhttp.EndpointRequest) (resbody []byte, err error) { + var res = libhttp.EndpointResponse{} + + res.Code = http.StatusOK + res.Data = epr.HttpRequest.MultipartForm.Value + + resbody, err = json.MarshalIndent(res, ``, ` `) + if err != nil { + return nil, err + } + + return resbody, nil +} -- cgit v1.3