github.com/blend/go-sdk@v1.20220411.3/r2/opt_path.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package r2
     9  
    10  import (
    11  	"fmt"
    12  	"net/url"
    13  	"strings"
    14  
    15  	"github.com/blend/go-sdk/ex"
    16  	"github.com/blend/go-sdk/stringutil"
    17  )
    18  
    19  // OptPath sets the url path.
    20  func OptPath(path string) Option {
    21  	return func(r *Request) error {
    22  		if r.Request == nil {
    23  			return ex.New(ErrRequestUnset)
    24  		}
    25  		if r.Request.URL == nil {
    26  			r.Request.URL = &url.URL{}
    27  		}
    28  		if !strings.HasPrefix(path, "/") {
    29  			path = "/" + path
    30  		}
    31  		r.Request.URL.Path = path
    32  		return nil
    33  	}
    34  }
    35  
    36  // OptPathf sets the url path based on a format and arguments.
    37  func OptPathf(format string, args ...interface{}) Option {
    38  	return OptPath(fmt.Sprintf(format, args...))
    39  }
    40  
    41  // OptPathParameterized sets the url path based on a parameterized path and arguments.
    42  // Parameterized paths should appear in the same format as paths you would add to your
    43  // web app (ex. `/resource/:resource_id`).
    44  func OptPathParameterized(format string, params map[string]string) Option {
    45  	return func(r *Request) error {
    46  		if r.Request == nil {
    47  			return ex.New(ErrRequestUnset)
    48  		}
    49  
    50  		if !strings.HasPrefix(format, "/") {
    51  			format = "/" + format
    52  		}
    53  
    54  		path, err := stringutil.ReplacePathParameters(format, params)
    55  		if err != nil {
    56  			return err
    57  		}
    58  
    59  		ctx := r.Request.Context()
    60  		r.WithContext(WithParameterizedPath(ctx, format))
    61  
    62  		return OptPath(path)(r)
    63  	}
    64  }