Skip to content

Instantly share code, notes, and snippets.

@cuixin
Created December 10, 2022 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuixin/4fc4f494f73ca8256c8a15fab6cbe23d to your computer and use it in GitHub Desktop.
Save cuixin/4fc4f494f73ca8256c8a15fab6cbe23d to your computer and use it in GitHub Desktop.
unquote nginx hex string in golang
package main
import (
"bytes"
"encoding/hex"
"fmt"
)
func UnquoteHex(str string) ([]byte, error) {
var (
ret bytes.Buffer
isQuote = false
)
for i := 0; i < len(str); i++ {
s := str[i]
if isQuote { // start dequote
if s == 'x' || s == 'X' {
if i+3 > len(str) {
return nil, fmt.Errorf("line hex is error")
}
hs, err := hex.DecodeString(str[i+1 : i+3])
if err != nil {
return nil, err
}
ret.WriteByte(hs[0])
i += 2 // the default i will be increased again, so it's 2
isQuote = false
} else {
return nil, fmt.Errorf("illegal dequote at [%v:%v]", i, s)
}
} else {
if s == '\\' {
isQuote = true // mark the dequote as starting
} else {
// it's not quoted
isQuote = false
if err := ret.WriteByte(byte(s)); err != nil {
return nil, err
}
}
}
}
return ret.Bytes(), nil
}
func main() {
testStr := `\x08\x16 \x02*` // you have to notice this using `, not to using ", if your declare a variable using ", golang will dequote \x automatically
desBytes, err := UnquoteHex(testStr)
if err != nil {
panic(err)
}
fmt.Println(desBytes) // [8 22 32 2 42]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment