0

I dont know what is the source of string it can be url encoded how do I test it whether it is a normal string or url encoded string this using this particular code

func decode(str1 string) { //str1 := "elementINPUT61599119%5B%5D" resl, err := url.QueryUnescape(str1) log.Println(err) return resl } func ifUrlEncoded(string string) bool{ if //function{ return true } return false } func main(){ if ifUrlEncoded(str){ fmt.Println(decode(str)) } else{ fmt.Println(str) } } 
6
  • 1
    Why? In what circumstance don't you already know? If you're the server, you know that it is encoded, for example, and if it isn't the request isn't valid. Commented Jun 3, 2022 at 9:39
  • @user207421 I want to create a function where I will check if url encoded call this go for decoding else continue. Commented Jun 3, 2022 at 9:43
  • 9
    Can you pose the question more precisely? If you don't know the source of the string, and you don't know if it was encoded or not, then you don't know because you don't know. For example, if you see "%20", maybe it's an encoded space character, or maybe it's literally supposed to be `'%', '2', '0'`` Commented Jun 3, 2022 at 9:53
  • 1
    I'm with @HymnsForDisco: in a typical code you always know this. For instance, in HTTP handlers the path component of the incoming request is decoded, so you just use it right away, and to obtain the query part of the URL, you call Query() on the request's URL field which deals with that. If your code is not related to handling requests, you have to guess. For instance, you could look for % in the URL, and if one found, decode it and then validate whether you got back a valid URL; if the result is not valid, the source URL was probably not encoded. Still, it will only be a guess. Commented Jun 3, 2022 at 11:10
  • It's like asking "How do I check if some byte sequence is encoded in ISO Latin 1?". You cannot tell from the byte sequence. Commented Jun 3, 2022 at 11:54

1 Answer 1

5

If I understand correctly, you want to find out if the string is able to be processed by QueryUnescape before passing it to QueryUnescape? If so, there's no need. If QueryUnescape is unable to process the string you gave, it will return an error.

decoded, err := url.QueryUnescape(originalString) if err != nil { // The string was not able to be decoded this way, so treat it as a "normal" string decoded = originalString } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.