Inital commit

This commit is contained in:
2022-02-24 01:07:09 +13:00
commit 8bc3cee328
55 changed files with 2292 additions and 0 deletions

31
misc/cookie/cookie.go Normal file
View File

@@ -0,0 +1,31 @@
package cookie
import (
"errors"
"net/http"
"time"
"git.1248.nz/1248/Otfe/misc/b64"
)
func Create(w http.ResponseWriter, name string, value string) {
c := &http.Cookie{Name: name, Value: b64.Encode(value)}
http.SetCookie(w, c)
}
func Read(r *http.Request, name string) (string, error) {
c, err := r.Cookie(name)
if err != nil {
return "", errors.New("Cookie not found")
}
value, err := b64.Decode(c.Value)
if err != nil {
return "", errors.New("Failed to decode cookie")
}
return value, nil
}
func Delete(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{Name: name, MaxAge: -1, Expires: time.Unix(1, 0)})
}

View File

@@ -0,0 +1,39 @@
package cookie
import (
"net/http"
"net/http/httptest"
"testing"
"git.1248.nz/1248/Otfe/misc/b64"
"git.1248.nz/1248/Otfe/misc/helpers"
)
func TestCreate(t *testing.T) {
recorder := httptest.NewRecorder()
Create(recorder, "test", "test")
request := &http.Request{Header: http.Header{
"Cookie": recorder.HeaderMap["Set-Cookie"]}}
cookie, err := request.Cookie("test")
if err != nil {
t.Fail()
return
}
value, err := b64.Decode(cookie.Value)
if err != nil || value != "test" {
t.Fail()
}
}
func TestRead(t *testing.T) {
cookie := &http.Cookie{Name: "test", Value: b64.Encode("test")}
request, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fail()
return
}
request.AddCookie(cookie)
value, err := Read(request, "test")
helpers.Equals(t, value, "test")
}