Skip to content

Commit 083fd95

Browse files
committed
feat(helpers): unsafe StringToBytes and BytesToString
1 parent 29a3be7 commit 083fd95

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

internal/client/client.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"encoding/json"
66
"errors"
7+
"github.com/kiasuo/bot/internal/helpers"
78
"github.com/kiasuo/bot/internal/users"
89
"net/http"
910
)
@@ -39,7 +40,7 @@ func httpRequest[T any](client Client, request *http.Request) (*http.Response, *
3940
}
4041

4142
func RefreshToken(client *Client) error {
42-
body := []byte(`{"refresh-token":"` + client.User.RefreshToken + `"}`)
43+
body := helpers.StringToBytes(`{"refresh-token":"` + client.User.RefreshToken + `"}`)
4344

4445
request, err := http.NewRequest("POST", BaseUrl+"/refresh", bytes.NewBuffer(body))
4546
request.Header.Set("Content-Type", "application/json")

internal/helpers/helpers.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package helpers
33
import (
44
"os"
55
"strings"
6+
"unsafe"
67
)
78

89
func If[T any](condition bool, truth, falsity T) T {
@@ -13,6 +14,14 @@ func If[T any](condition bool, truth, falsity T) T {
1314
return falsity
1415
}
1516

17+
func StringToBytes(str string) []byte {
18+
return unsafe.Slice(unsafe.StringData(str), len(str))
19+
}
20+
21+
func BytesToString(bytes []byte) string {
22+
return unsafe.String(unsafe.SliceData(bytes), len(bytes))
23+
}
24+
1625
func GetEnv(key string) string {
1726
value, ok := os.LookupEnv(key)
1827

@@ -29,7 +38,7 @@ func GetEnv(key string) string {
2938
panic(err)
3039
}
3140

32-
return strings.TrimSpace(string(buffer))
41+
return strings.TrimSpace(BytesToString(buffer))
3342
}
3443

3544
panic("Environment variable " + key + " not set")

internal/helpers/helpers_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,22 @@ func TestIfFalse(t *testing.T) {
2121
}
2222
}
2323

24+
func TestStringToBytes(t *testing.T) {
25+
result := StringToBytes("test")
26+
27+
if string(result) != "test" {
28+
t.Errorf("StringToBytes() = %s; want test", result)
29+
}
30+
}
31+
32+
func TestBytesToString(t *testing.T) {
33+
result := BytesToString([]byte("test"))
34+
35+
if result != "test" {
36+
t.Errorf("BytesToString() = %s; want test", result)
37+
}
38+
}
39+
2440
func TestGetEnvPath(t *testing.T) {
2541
// I think PATH variable is set on every system
2642
GetEnv("PATH")

0 commit comments

Comments
 (0)