From 8d27c8b6fa922fbb90bde8ba3675abf535d12422 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 16 Feb 2024 01:37:11 +0700 Subject: all: add default HTTPRunHandler Previously, the default HTTPRunHandler is hidden, called dynamically based on Run is nil or not. This changes make it exported as function that return HTTPRunHandler to show how define and create a custom HTTPRunHandler. --- http_run_handler.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 http_run_handler.go (limited to 'http_run_handler.go') diff --git a/http_run_handler.go b/http_run_handler.go new file mode 100644 index 0000000..00212ec --- /dev/null +++ b/http_run_handler.go @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2024 M. Shulhan +// SPDX-License-Identifier: GPL-3.0-or-later + +package gorankusu + +import ( + "bytes" + "fmt" + "io" + "net/http" + + libhttp "github.com/shuLhan/share/lib/http" +) + +// HTTPRunHandler define the function type that will be called when client +// send request to run the HTTP target. +type HTTPRunHandler func(rr *RunRequest) (runres *RunResponse, err error) + +// DefaultHTTPRun default [HTTPTarget.Run] handler that generate +// [http.Request], send it to the target, and store and dump them into +// [RunResponse]. +func DefaultHTTPRun() HTTPRunHandler { + return func(rr *RunRequest) (res *RunResponse, err error) { + var ( + logp = `DefaultHTTPRun` + httpcOpts = &libhttp.ClientOptions{ + ServerUrl: rr.Target.BaseURL, + AllowInsecure: true, + } + httpc = libhttp.NewClient(httpcOpts) + params any + ) + + if !rr.HTTPTarget.WithRawBody { + rr.HTTPTarget.paramsToPath() + + params, err = rr.HTTPTarget.ParamsConverter(&rr.HTTPTarget) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + } + + var ( + headers = rr.HTTPTarget.Headers.ToHTTPHeader() + + httpRequest *http.Request + ) + + httpRequest, err = httpc.GenerateHttpRequest( + rr.HTTPTarget.Method, + rr.HTTPTarget.Path, + rr.HTTPTarget.RequestType, + headers, + params, + ) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + if rr.HTTPTarget.WithRawBody { + httpRequest.Body = io.NopCloser(bytes.NewReader(rr.HTTPTarget.RawBody)) + httpRequest.ContentLength = int64(len(rr.HTTPTarget.RawBody)) + } + + res = &RunResponse{} + + err = res.SetHTTPRequest(rr.HTTPTarget.RequestDumper, httpRequest) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + var httpResponse *http.Response + + httpResponse, _, err = httpc.Do(httpRequest) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + err = res.SetHTTPResponse(rr.HTTPTarget.ResponseDumper, httpResponse) + if err != nil { + return nil, fmt.Errorf(`%s: %w`, logp, err) + } + + return res, nil + } +} -- cgit v1.3-6-g1900