Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URL Encoder and decoder #12

Merged
merged 1 commit into from
Jun 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions pkg/pencode/encoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package pencode

import (
"fmt"
"sort"
)

var availableEncoders = map[string]Encoder{
"b64encode": Base64Encoder{},
"b64decode": Base64Decoder{},
"b64encode": Base64Encoder{},
"b64decode": Base64Decoder{},
"urlencode": URLEncoder{},
"urldecode": URLDecoder{},
"urlencodeall": URLEncoderAll{},
}

type Chain struct {
Expand Down Expand Up @@ -69,7 +73,15 @@ func (c *Chain) Usage() {
}
format := fmt.Sprintf(" %%-%ds- %%s\n", max_length+2)

for k, v := range availableEncoders {
fmt.Printf(format, k, v.HelpText())
// Sort the encoders alphabetically
names := make([]string, 0, len(availableEncoders))
for k := range availableEncoders {
names = append(names, k)
}
sort.Strings(names)

for _, n := range names {
v := availableEncoders[n]
fmt.Printf(format, n, v.HelpText())
}
}
19 changes: 19 additions & 0 deletions pkg/pencode/urldecode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package pencode

import (
"net/url"
)

type URLDecoder struct{}

func (u URLDecoder) Encode(input []byte) ([]byte, error) {
output, err := url.QueryUnescape(string(input))
if err != nil {
return []byte{}, err
}
return []byte(output), err
}

func (u URLDecoder) HelpText() string {
return "URL decode"
}
15 changes: 15 additions & 0 deletions pkg/pencode/urlencode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package pencode

import (
"net/url"
)

type URLEncoder struct{}

func (u URLEncoder) Encode(input []byte) ([]byte, error) {
return []byte(url.QueryEscape(string(input))), nil
}

func (u URLEncoder) HelpText() string {
return "URL encode reserved characters"
}
24 changes: 24 additions & 0 deletions pkg/pencode/urlencodeall.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package pencode

import (
"bytes"
)

const upperhex = "0123456789ABCDEF"

type URLEncoderAll struct{}

func (u URLEncoderAll) Encode(input []byte) ([]byte, error) {
var buf bytes.Buffer
for _, c := range input {
// Add "%"
buf.WriteByte(37)
buf.WriteByte(upperhex[c>>4])
buf.WriteByte(upperhex[c&15])
}
return buf.Bytes(), nil
}

func (u URLEncoderAll) HelpText() string {
return "URL encode all characters"
}