Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OptionalHeader, OptionalParam #105

Merged
merged 8 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions builder_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import (
// then customize it with
// [Builder.Scheme], [Builder.Host], [Builder.Hostf], [Builder.Path],
// [Builder.Pathf], [Builder.Param], and [Builder.ParamInt].
// [Builder.ParamOptional] can be used to add a query parameter
// only if it has not been otherwise set.
//
// # Build an http.Request with Builder.Request
//
Expand All @@ -37,6 +39,8 @@ import (
// or set conventional header keys with
// [Builder.Accept], [Builder.BasicAuth], [Builder.Bearer], [Builder.CacheControl],
// [Builder.ContentType], [Builder.Cookie], and [Builder.UserAgent].
// [Builder.HeaderOptional] can be used to add a header
// only if it has not been otherwise set.
//
// Set the body of the request, if any, with [Builder.Body]
// or use built in [Builder.BodyBytes], [Builder.BodyFile], [Builder.BodyForm],
Expand Down Expand Up @@ -117,12 +121,28 @@ func (rb *Builder) Param(key string, values ...string) *Builder {
return rb
}

// ParamOptional sets a query parameter on a Builder's URL
// only if it is not set by some other call to Param or ParamOptional
// and one of the values is a non-blank string.
func (rb *Builder) ParamOptional(key string, values ...string) *Builder {
rb.ub.ParamOptional(key, values...)
return rb
}

// Header sets a header on a request. It overwrites the existing values of a key.
func (rb *Builder) Header(key string, values ...string) *Builder {
rb.rb.Header(key, values...)
return rb
}

// HeaderOptional sets a header on a request
// only if it has not already been set by another call to Header or HeaderOptional
// and one of the values is a non-blank string.
func (rb *Builder) HeaderOptional(key string, values ...string) *Builder {
rb.rb.HeaderOptional(key, values...)
return rb
}

// Cookie adds a cookie to a request.
// Unlike other headers, adding a cookie does not overwrite existing values.
func (rb *Builder) Cookie(name, value string) *Builder {
Expand Down
43 changes: 43 additions & 0 deletions builder_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -706,3 +706,46 @@ func ExampleBuilder_BodyJSON() {
// ]
// }
}

func ExampleBuilder_ParamOptional() {
// Suppose we have some variables from some external source
yes := "1"
no := ""

u, err := requests.
URL("https://www.example.com/?c=something").
ParamOptional("a", yes).
ParamOptional("b", no). // Won't set ?b= because no is blank
ParamOptional("c", yes). // Won't set ?c= because it was already in the base URL
URL()
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(u.String())

// Output:
// https://www.example.com/?a=1&c=something
}

func ExampleBuilder_HeaderOptional() {
// Suppose we have some environment variables
// which may or may not be set
env := map[string]string{
"FOO": "1",
"BAR": "",
"BAZ": "",
}
req, err := requests.
URL("https://example.com").
HeaderOptional("X-FOO", env["FOO"]).
HeaderOptional("X-BAR", env["BAR"]). // Won't set because BAR is blank
Header("X-BAZ", env["BAZ"]). // Will set to "" because it's not optional
Request(context.Background())
if err != nil {
fmt.Println("Error!", err)
}
fmt.Println(req.Header)

// Output:
// map[X-Baz:[] X-Foo:[1]]
}
5 changes: 3 additions & 2 deletions builder_extras.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,12 @@ func (rb *Builder) BodySerializer(s Serializer, v any) *Builder {

// BodyJSON sets the Builder's request body to the marshaled JSON.
// It uses [JSONSerializer] to marshal the object.
// It also sets ContentType to "application/json".
// It also sets ContentType to "application/json"
// if it is not otherwise set.
func (rb *Builder) BodyJSON(v any) *Builder {
return rb.
Body(BodyJSON(v)).
ContentType("application/json")
HeaderOptional("Content-Type", "application/json")
}

// BodyForm sets the Builder's request body to the encoded form.
Expand Down
17 changes: 15 additions & 2 deletions core_req.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ type requestBuilder struct {
}

func (rb *requestBuilder) Header(key string, values ...string) {
rb.headers = append(rb.headers, multimap{key, values})
rb.headers = append(rb.headers, multimap{key, values, false})
}

func (rb *requestBuilder) HeaderOptional(key string, values ...string) {
rb.headers = append(rb.headers, multimap{key, values, true})
}

func (rb *requestBuilder) Cookie(name, value string) {
Expand Down Expand Up @@ -80,7 +84,16 @@ func (rb *requestBuilder) Request(ctx context.Context, u *url.URL) (req *http.Re
req.GetBody = rb.getBody

for _, kv := range rb.headers {
req.Header[http.CanonicalHeaderKey(kv.key)] = kv.values
if !kv.optional {
req.Header[http.CanonicalHeaderKey(kv.key)] = kv.values
}
}
for _, kv := range rb.headers {
if kv.optional &&
req.Header.Get(kv.key) == "" &&
minitrue.Or(kv.values...) != "" {
req.Header[http.CanonicalHeaderKey(kv.key)] = kv.values
}
}
for _, kv := range rb.cookies {
req.AddCookie(&http.Cookie{
Expand Down
22 changes: 18 additions & 4 deletions core_url.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import (
)

type multimap struct {
key string
values []string
key string
values []string
optional bool
}

type kvpair struct {
Expand Down Expand Up @@ -41,7 +42,11 @@ func (ub *urlBuilder) Path(path string) {
}

func (ub *urlBuilder) Param(key string, values ...string) {
ub.params = append(ub.params, multimap{key, values})
ub.params = append(ub.params, multimap{key, values, false})
}

func (ub *urlBuilder) ParamOptional(key string, values ...string) {
ub.params = append(ub.params, multimap{key, values, true})
}

func (ub *urlBuilder) Clone() *urlBuilder {
Expand All @@ -68,7 +73,16 @@ func (ub *urlBuilder) URL() (u *url.URL, err error) {
if len(ub.params) > 0 {
q := u.Query()
for _, kv := range ub.params {
q[kv.key] = kv.values
if !kv.optional {
q[kv.key] = kv.values
}
}
for _, kv := range ub.params {
if kv.optional &&
q.Get(kv.key) == "" &&
minitrue.Or(kv.values...) != "" {
q[kv.key] = kv.values
}
}
u.RawQuery = q.Encode()
}
Expand Down
5 changes: 3 additions & 2 deletions reqxml/body.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ func Body(v any) requests.BodyGetter {
}

// BodyConfig sets the Builder's request body to the marshaled XML.
// It also sets ContentType to "application/xml".
// It also sets ContentType to "application/xml"
// if it is not otherwise set.
func BodyConfig(v any) requests.Config {
return func(rb *requests.Builder) {
rb.
Body(Body(v)).
ContentType("application/xml")
HeaderOptional("Content-Type", "application/xml")
}
}
Loading