Skip to content

Commit

Permalink
feat(libserver,libsession): adding a few cookies management function …
Browse files Browse the repository at this point in the history
…and implementing a session api.
  • Loading branch information
razshare committed Feb 1, 2025
1 parent 7b489f5 commit a2c96de
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 30 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.23
require (
github.com/evanw/esbuild v0.24.2
github.com/gorilla/websocket v1.5.3
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d
rogchap.com/v8go v0.9.0
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/evanw/esbuild v0.24.2 h1:PQExybVBrjHjN6/JJiShRGIXh1hWVm6NepVnhZhrt0A=
github.com/evanw/esbuild v0.24.2/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ=
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
Expand Down
10 changes: 5 additions & 5 deletions libprepare.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ func PrepareStart() {

// PrepareEnd ends preparation by generating all prepared code.
func PrepareEnd() {
dumpSvelteFiles()
dumpSveltePages()
}

func dumpSvelteFiles() {
func dumpSveltePages() {
if !Exists("www/.frizzante/vite-project") {
err := os.MkdirAll("www/.frizzante/vite-project", os.ModePerm)
if err != nil {
Expand All @@ -128,11 +128,11 @@ func dumpSvelteFiles() {

var builder strings.Builder
counter := 0
for id, fileName := range sveltePagesToFileNames {
for pageId, fileName := range sveltePagesToFileNames {
if 0 == counter {
builder.WriteString(fmt.Sprintf("{#if '%s' === reactivePageId}\n", id))
builder.WriteString(fmt.Sprintf("{#if '%s' === reactivePageId}\n", pageId))
} else {
builder.WriteString(fmt.Sprintf("{:else if '%s' === reactivePageId}\n", id))
builder.WriteString(fmt.Sprintf("{:else if '%s' === reactivePageId}\n", pageId))
}
builder.WriteString(fmt.Sprintf(" <Async from={import('%s')} />\n", fileName))
counter++
Expand Down
20 changes: 20 additions & 0 deletions libserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,21 @@ func ServerTemporaryDirectoryClear(self *Server) {
}
}

// ReceiveCookie reads the contents of a cookie from the message and returns the value.
func ReceiveCookie(self *Request, key string) string {
cookie, cookieError := self.HttpRequest.Cookie(key)
if cookieError != nil {
ServerNotifyError(self.server, cookieError)
return ""
}
value, unescapeError := url.QueryUnescape(cookie.Value)
if unescapeError != nil {
return ""
}

return value
}

// ReceiveMessage reads the contents of the message and returns the value.
func ReceiveMessage(self *Request) string {
if self.webSocket != nil {
Expand Down Expand Up @@ -601,6 +616,11 @@ func SendHeader(self *Response, key string, value string) {
self.header.Set(key, value)
}

// SendCookie sends a cookies to the client.
func SendCookie(self *Response, key string, value string) {
SendHeader(self, "Set-Cookie", fmt.Sprintf("%s=%s", url.QueryEscape(key), url.QueryEscape(value)))
}

// SendContent sends binary safe content.
//
// If the status code or the header have not been sent already, a default status of "200 OK" will be sent immediately along with whatever headers you've previously defined.
Expand Down
84 changes: 84 additions & 0 deletions libsession.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package frizzante

import "github.com/nu7hatch/gouuid"

var sessions = map[string]*Session{}

type Session struct {
id string
data map[string]interface{}
}

func (s *Session) get(key string, defaultValue interface{}) interface{} {
sessionItem, ok := s.data[key]
if !ok {
s.data[key] = defaultValue
return s.data[key]
}

return sessionItem
}

func (s *Session) set(key string, defaultValue interface{}) {
s.data[key] = defaultValue
}

func sessionCreate() (*Session, error) {
sessionId, uuidError := uuid.NewV4()
if uuidError != nil {
return nil, uuidError
}

return &Session{
id: sessionId.String(),
data: map[string]interface{}{},
}, nil
}

// SessionStart starts a new session or retrieves it if it's already been started.
//
// SessionStart always returns two functions, a get() and a set(), which you can use to manage the session.
func SessionStart(request *Request, response *Response) (
get func(key string, defaultValue interface{}) interface{},
set func(key string, defaultValue interface{}),
) {
sessionIdCookie, cookieError := request.HttpRequest.Cookie("session-id")
if cookieError != nil {
freshSession, sessionError := sessionCreate()
if sessionError != nil {
ServerNotifyError(request.server, sessionError)
return nil, nil
}

SendCookie(response, "session-id", freshSession.id)
sessions[freshSession.id] = freshSession
get = freshSession.get
set = freshSession.set
return
}

session, sessionExists := sessions[sessionIdCookie.Value]
if !sessionExists {
freshSession, sessionError := sessionCreate()
if sessionError != nil {
ServerNotifyError(request.server, sessionError)
return nil, nil
}

SendCookie(response, "session-id", freshSession.id)
sessions[freshSession.id] = freshSession
get = freshSession.get
set = freshSession.set
return
}

SendCookie(response, "session-id", sessionIdCookie.Value)
get = session.get
set = session.set
return
}

// SessionDestroy destroys the session.
func SessionDestroy(self *Session) {
delete(sessions, self.id)
}
47 changes: 24 additions & 23 deletions makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ clean:
rm cert.pem -f
rm key.pem -f
rm bin/app -f
rm generated -fr
rm tmp -fr
rm www/dist -fr
mkdir www/dist/server -p
Expand All @@ -15,28 +16,28 @@ clean:
touch www/dist/server/.gitkeep
touch www/dist/client/.gitkeep

build: www-build main.go go.mod
CGO_ENABLED=1 go build -o bin/app .

start: www-build main.go go.mod
CGO_ENABLED=1 go run main.go

dev: air main.go go.mod
DEV=1 CGO_ENABLED=1 ./bin/air \
--build.cmd "go run github.com/razshare/frizzante/prepare && go build -o bin/app ." \
--build.bin "bin/app" \
--build.exclude_dir "out,tmp,bin,www/.frizzante,www/dist,www/node_modules,www/tmp" \
--build.exclude_regex "_text.go" \
--build.include_ext "go,svelte,js,json" \
--build.log "go-build-errors.log" & make www-watch & wait

air:
which bin/air || curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

www-prepare:
go run github.com/razshare/frizzante/prepare

www-build: www-prepare www/package.json
#build: www-build main.go go.mod
# CGO_ENABLED=1 go build -o bin/app .
#
#start: www-build main.go go.mod
# CGO_ENABLED=1 go run main.go
#
#dev: air main.go go.mod
# DEV=1 CGO_ENABLED=1 ./bin/air \
# --build.cmd "go run github.com/razshare/frizzante/generate && go build -o bin/app ." \
# --build.bin "bin/app" \
# --build.exclude_dir "out,tmp,bin,www/.frizzante,www/dist,www/node_modules,www/tmp" \
# --build.exclude_regex "_text.go" \
# --build.include_ext "go,svelte,js,json" \
# --build.log "go-build-errors.log" & make www-watch & wait
#
#air:
# which bin/air || curl -sSfL https://raw.githubusercontent.com/air-verse/air/master/install.sh | sh -s

configure:
go run prepare/main.go

www-build: configure www/package.json
make www-build-server & make www-build-client & wait

www-build-server: www/package.json
Expand All @@ -48,7 +49,7 @@ www-build-client: www/package.json
cd www && \
bunx vite build --outDir dist/client --emptyOutDir

www-watch: www-prepare www/package.json
www-watch: configure www/package.json
make www-watch-server & make www-watch-client & wait

www-watch-server: www/package.json
Expand Down
2 changes: 1 addition & 1 deletion www/bun.lock
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@

"statuses": ["[email protected]", "", {}, "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="],

"svelte": ["[email protected].5", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@jridgewell/sourcemap-codec": "^1.5.0", "@types/estree": "^1.0.5", "acorn": "^8.12.1", "acorn-typescript": "^1.4.13", "aria-query": "^5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "esm-env": "^1.2.1", "esrap": "^1.4.3", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-vVAntseegJX80sgbY8CxQISSE/VoDSfP7VZHoQaf2+z+2XOPOz/N+k455HJmO9O0g8oxTtuE0TBhC/5LAP4lPg=="],
"svelte": ["[email protected].6", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@jridgewell/sourcemap-codec": "^1.5.0", "@types/estree": "^1.0.5", "acorn": "^8.12.1", "acorn-typescript": "^1.4.13", "aria-query": "^5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "esm-env": "^1.2.1", "esrap": "^1.4.3", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-6ydekB3qyqUal+UhfMjmVOjRGtxysR8vuiMhi2nwuBtPJWnctVlsGspjVFB05qmR+TXI1emuqtZt81c0XiFleA=="],

"toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],

Expand Down
2 changes: 1 addition & 1 deletion www/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"compression": "^1.7.5",
"express": "^4.21.2",
"sirv": "^3.0.0",
"svelte": "^5.19.5",
"svelte": "^5.19.6",
"vite": "^6.0.11"
}
}

0 comments on commit a2c96de

Please sign in to comment.