Skip to content

Commit

Permalink
cm: Add proper readme
Browse files Browse the repository at this point in the history
  • Loading branch information
fingon committed Apr 28, 2024
1 parent f545961 commit b5fd552
Showing 1 changed file with 55 additions and 13 deletions.
68 changes: 55 additions & 13 deletions cm/README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,68 @@
# Cookie Monster #
# Cookie Monster (aka cm)

This sublibrary (someday perhaps available separately, but for now, not) is
convenience wrapper for handling client state in client (fully in the
cookie). For now, the state is not encrypted at all (although we could), as
I do not really see the point. The idea is not to store secrets using this,
just e.g. state in various views so that the client resumes same state
convenience wrapper for handling client state in server (fully in the
cookie).

For now, the state is not encrypted at all (although we could), as I do not
really see the point. The idea is not to store secrets using this, just
e.g. state in various views so that the client resumes same state
implicitly when they go back to a view.


## Short form

Define state as normal struct, e.g.

```
err = monster.Run(r, w, &state)
type State struct {
Number int `json:"n" cm:"number"`
}
```

Where
and then call

```
r = http.Request
w = http.ResponseWriter
state = arbitrary struct (ideally empty)
err = cm.Run(r, w, &state)
```

Where
- `r`: `http.Request`
- `w`: `http.ResponseWriter`
- `state`: arbitrary struct with cm + json tags (ideally empty but this will clear most of the state)

The struct is examined through reflection and `cm:"field"` entries are
CRUDed based on `"field"` in the `http.Request`. Note that json definitions
must be also supplied for the fields, or otherwise they will not be
imported/exported.
CRUDed based on `"field"` in the `http.Request.Form`. They are persisted
automagically to cookie derived from the struct name, and with the `json`
tagged names (preferably short ones, as cookie space is limited). If json
definitions are not supplied, they will not be imported/exported.

## Supported datatypes

Currently the code supports only following datatypes:

- bool
- int*
- string
- uint*

Other types, if tagged, cause an error.

## What does it do?

The above cm.Run call will:

- read existing json cookie with name `cm.<module>.State` and unmarshal
JSON content from it to the State struct
- reads query parameter 'number', and if it is set, update `state` instance
- (.. same with other fields too, if any ..)
- if any of the fields were updated, set the updated cookie for the
response

## TODO

- Perhaps make the configuration also accept Path? For now, cookies are
scoped to Path "/" so e.g. global state can be used to convey them; this
may not be optimal always.

- Document this better?

0 comments on commit b5fd552

Please sign in to comment.