cuelang.org/go@v0.13.0/pkg/net/url.go (about)

     1  // Copyright 2019 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package net
    16  
    17  import (
    18  	"errors"
    19  	"net/url"
    20  )
    21  
    22  // PathEscape escapes the string so it can be safely placed inside a URL path
    23  // segment, replacing special characters (including /) with %XX sequences as
    24  // needed.
    25  func PathEscape(s string) string {
    26  	return url.PathEscape(s)
    27  }
    28  
    29  // PathUnescape does the inverse transformation of PathEscape, converting each
    30  // 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB.
    31  // It returns an error if any % is not followed by two hexadecimal digits.
    32  //
    33  // PathUnescape is identical to QueryUnescape except that it does not unescape
    34  // '+' to ' ' (space).
    35  func PathUnescape(s string) (string, error) {
    36  	return url.PathUnescape(s)
    37  }
    38  
    39  // QueryEscape escapes the string so it can be safely placed inside a URL
    40  // query.
    41  func QueryEscape(s string) string {
    42  	return url.QueryEscape(s)
    43  }
    44  
    45  // QueryUnescape does the inverse transformation of QueryEscape, converting
    46  // each 3-byte encoded substring of the form "%AB" into the hex-decoded byte
    47  // 0xAB. It returns an error if any % is not followed by two hexadecimal
    48  // digits.
    49  func QueryUnescape(s string) (string, error) {
    50  	return url.QueryUnescape(s)
    51  }
    52  
    53  // URL validates that s is a valid relative or absolute URL.
    54  // Note: this does also allow non-ASCII characters.
    55  func URL(s string) (bool, error) {
    56  	_, err := url.Parse(s)
    57  	return err == nil, err
    58  }
    59  
    60  // URL validates that s is an absolute URL.
    61  // Note: this does also allow non-ASCII characters.
    62  func AbsURL(s string) (bool, error) {
    63  	u, err := url.Parse(s)
    64  	if err != nil {
    65  		return false, err
    66  	}
    67  	if !u.IsAbs() {
    68  		return false, errors.New("URL is not absolute")
    69  	}
    70  	return true, nil
    71  }