aboutsummaryrefslogtreecommitdiff
path: root/lib/http/client_example_test.go
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2024-02-15 02:28:30 +0700
committerShulhan <ms@kilabit.info>2024-02-15 02:28:30 +0700
commit6ef5bdfc203a5d5e3648c59edd158db51ee289c0 (patch)
tree3352b1740abe5a5c6c6177e5c2b6fc758564bd7b /lib/http/client_example_test.go
parent48e6dced72d470d78c8f58f4dc703528eb092c3c (diff)
downloadpakakeh.go-6ef5bdfc203a5d5e3648c59edd158db51ee289c0.tar.xz
lib/http: export function to generate "multipart/form-data"
The GenerateFormData generate the request body with boundary for HTTP content-type "multipart/form-data" from map[string][]byte.
Diffstat (limited to 'lib/http/client_example_test.go')
-rw-r--r--lib/http/client_example_test.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/lib/http/client_example_test.go b/lib/http/client_example_test.go
new file mode 100644
index 00000000..2d7d3bdf
--- /dev/null
+++ b/lib/http/client_example_test.go
@@ -0,0 +1,47 @@
+package http_test
+
+import (
+ "crypto/rand"
+ "fmt"
+ "log"
+ "strings"
+
+ libhttp "github.com/shuLhan/share/lib/http"
+ "github.com/shuLhan/share/lib/test/mock"
+)
+
+func ExampleGenerateFormData() {
+ // Mock the random reader for predictable output.
+ // NOTE: do not do this on real code.
+ rand.Reader = mock.NewRandReader([]byte(`randomseed`))
+
+ var data = map[string][]byte{
+ `name`: []byte(`test.txt`),
+ `size`: []byte(`42`),
+ }
+
+ var (
+ contentType string
+ body string
+ err error
+ )
+ contentType, body, err = libhttp.GenerateFormData(data)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println(`contentType:`, contentType)
+ fmt.Println(`body:`)
+ fmt.Println(strings.ReplaceAll(body, "\r\n", "\n"))
+ // Output:
+ // contentType: multipart/form-data; boundary=72616e646f6d7365656472616e646f6d7365656472616e646f6d73656564
+ // body:
+ // --72616e646f6d7365656472616e646f6d7365656472616e646f6d73656564
+ // Content-Disposition: form-data; name="name"
+ //
+ // test.txt
+ // --72616e646f6d7365656472616e646f6d7365656472616e646f6d73656564
+ // Content-Disposition: form-data; name="size"
+ //
+ // 42
+ // --72616e646f6d7365656472616e646f6d7365656472616e646f6d73656564--
+}