github.com/google/syzkaller@v0.0.0-20251211124644-a066d2bc4b02/pkg/html/urlutil/urls.go (about)

     1  // Copyright 2025 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package urlutil
     5  
     6  import "net/url"
     7  
     8  // SetParam overrides the specific key from the URL.
     9  // It does not take into account that there may be multiple parameters with the same name.
    10  func SetParam(baseURL, key, value string) string {
    11  	return TransformParam(baseURL, key, func(_ []string) []string {
    12  		if value == "" {
    13  			return nil
    14  		}
    15  		return []string{value}
    16  	})
    17  }
    18  
    19  // DropParam removes the specific key=value pair from the URL
    20  // (it's possible to have many of parameters with the same name).
    21  // Set value="" to remove the key regardless of the value.
    22  func DropParam(baseURL, key, value string) string {
    23  	return TransformParam(baseURL, key, func(oldValues []string) []string {
    24  		if value == "" {
    25  			return nil
    26  		}
    27  		var newValues []string
    28  		for _, iterVal := range oldValues {
    29  			if iterVal != value {
    30  				newValues = append(newValues, iterVal)
    31  			}
    32  		}
    33  		return newValues
    34  	})
    35  }
    36  
    37  // TransformParam is a generic method that transforms the set of values
    38  // for the specified URL parameter key.
    39  func TransformParam(baseURL, key string, f func([]string) []string) string {
    40  	if baseURL == "" {
    41  		return ""
    42  	}
    43  	parsed, err := url.Parse(baseURL)
    44  	if err != nil {
    45  		return ""
    46  	}
    47  	values := parsed.Query()
    48  	ret := f(values[key])
    49  	if len(ret) == 0 {
    50  		values.Del(key)
    51  	} else {
    52  		values[key] = ret
    53  	}
    54  	parsed.RawQuery = values.Encode()
    55  	return parsed.String()
    56  }