Skip to content

Commit 474fa6a

Browse files
committed
remove zerlog + panic
1 parent 420c0bd commit 474fa6a

20 files changed

+449
-479
lines changed

chain.go

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,11 @@
11
package chain
22

3-
import (
4-
"github.com/rs/zerolog"
5-
"github.com/rs/zerolog/log"
6-
"os"
7-
"time"
8-
)
9-
10-
func _l(msg string) string {
11-
return "[chain] " + msg
12-
}
13-
14-
func init() {
15-
log.Logger = log.Output(zerolog.ConsoleWriter{
16-
Out: os.Stderr,
17-
TimeFormat: time.RFC3339,
18-
})
19-
}
20-
213
func New() *Router {
224
router := &Router{
23-
RedirectTrailingSlash: true,
5+
HandleOPTIONS: true,
246
RedirectFixedPath: true,
7+
RedirectTrailingSlash: true,
258
HandleMethodNotAllowed: true,
26-
HandleOPTIONS: true,
279
}
2810
router.contextPool.New = func() any {
2911
return &Context{}

context.go

Lines changed: 8 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,11 @@ type Context struct {
3535
MatchedRoutePath string
3636
Writer http.ResponseWriter
3737
Request *http.Request
38-
Crypto *cryptoShortcuts
38+
Crypto *cryptoImpl
3939
root *Context
4040
children []*Context
4141
}
4242

43-
// async(runnable) // lifts request out of Jetty's ThreadPool, and moves it to Javalin's AsyncThreadPool
44-
// async(asyncConfig, runnable) // same as above, but with additonal config
45-
// handlerType() // handler type of the current handler (BEFORE, AFTER, GET, etc)
46-
// appData(typedKey) // get data from the Javalin instance (see app data section below)
47-
// with(pluginClass) // get context plugin by class, see plugin section below
48-
// matchedPath() // get the path that was used to match this request (ex, "/hello/{name}")
49-
// endpointHandlerPath() // get the path of the endpoint handler that was used to match this request
50-
// cookieStore() // see cookie store section below
51-
// skipRemainingHandlers() // skip all remaining handlers for this request
52-
5343
// Set define um valor compartilhado no contexto de execução da requisição
5444
func (ctx *Context) Set(key any, value any) {
5545
if ctx.root != nil {
@@ -62,34 +52,16 @@ func (ctx *Context) Set(key any, value any) {
6252
}
6353

6454
// Get obtém um valor compartilhado no contexto de execução da requisição
65-
func (ctx *Context) Get(key any) any {
55+
func (ctx *Context) Get(key any) (any, bool) {
6656
if ctx.root != nil {
6757
return ctx.root.Get(key)
6858
}
6959

7060
if ctx.data == nil {
71-
return nil
72-
}
73-
if value, exists := ctx.data[key]; exists {
74-
return value
61+
return nil, false
7562
}
76-
return nil
77-
}
78-
79-
// GetParam returns the value of the first Param which key matches the given name.
80-
// If no matching Param is found, an empty string is returned.
81-
func (ctx *Context) GetParam(name string) string {
82-
for i := 0; i < ctx.paramCount; i++ {
83-
if ctx.paramNames[i] == name {
84-
return ctx.paramValues[i]
85-
}
86-
}
87-
return ""
88-
}
89-
90-
// GetParamByIndex get one parameter per index
91-
func (ctx *Context) GetParamByIndex(index int) string {
92-
return ctx.paramValues[index]
63+
value, exists := ctx.data[key]
64+
return value, exists
9365
}
9466

9567
func (ctx *Context) WithParams(names []string, values []string) *Context {
@@ -145,21 +117,21 @@ func (ctx *Context) Router() *Router {
145117
// Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
146118
func (ctx *Context) BeforeSend(callback func()) error {
147119
if spy, is := ctx.Writer.(*ResponseWriterSpy); is {
148-
return spy.beforeSend(callback)
120+
return spy.beforeWriteHeader(callback)
149121
}
150122
return nil
151123
}
152124

153125
func (ctx *Context) AfterSend(callback func()) error {
154126
if spy, is := ctx.Writer.(*ResponseWriterSpy); is {
155-
return spy.afterSend(callback)
127+
return spy.afterWrite(callback)
156128
}
157129
return nil
158130
}
159131

160132
func (ctx *Context) write() {
161133
if spy, is := ctx.Writer.(*ResponseWriterSpy); is {
162-
if !spy.wrote {
134+
if !spy.writeStarted {
163135
ctx.WriteHeader(http.StatusOK)
164136
}
165137
}

context_request.go

Lines changed: 40 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,12 @@ import (
44
"io"
55
"net/http"
66
"net/url"
7+
"strconv"
78
)
89

9-
// BodyAs(obj) err // request body as specified class (deserialized from JSON)
10-
// QueryAs(obj) err // request body as specified class (deserialized from JSON)
11-
12-
// Request methods
13-
// body() // request body as string
14-
// bodyAsBytes() // request body as array of bytes
15-
1610
// BodyBytes get body as array of bytes
1711
func (ctx *Context) BodyBytes() (body []byte, err error) {
18-
if cb := ctx.Get(BodyBytesKey); cb != nil {
12+
if cb, exist := ctx.Get(BodyBytesKey); exist && cb != nil {
1913
if cbb, ok := cb.([]byte); ok {
2014
body = cbb
2115
}
@@ -32,51 +26,47 @@ func (ctx *Context) BodyBytes() (body []byte, err error) {
3226
return
3327
}
3428

35-
// bodyStreamAsClass(clazz) // request body as specified class (memory optimized version of above)
36-
// bodyValidator(clazz) // request body as validator typed as specified class
37-
// bodyInputStream() // the underyling input stream of the request
38-
39-
// formParam("name") // form parameter by name, as string
40-
// formParamAsClass("name", clazz) // f orm parameter by name, as validator typed as specified class
41-
// formParams("name") // list of form parameters by name
42-
// formParamMap() // map of all form parameters
43-
44-
// pathParam("name") // path parameter by name as string
45-
// pathParamAsClass("name", clazz) // path parameter as validator typed as specified class
46-
// pathParamMap() // map of all path parameters
47-
48-
// queryParam("name") // query param by name as string
49-
// queryParamAsClass("name", clazz) // query param parameter by name, as validator typed as specified class
50-
// queryParams("name") // list of query parameters by name
51-
// queryParamMap() // map of all query parameters
52-
// queryString() // full query string
53-
54-
// uploadedFile("name") // uploaded file by name
55-
// uploadedFiles("name") // all uploaded files by name
56-
// uploadedFiles() // all uploaded files as list
57-
// uploadedFileMap() // all uploaded files as a "names by files" map
58-
59-
// basicAuthCredentials() // basic auth credentials (or null if not set)
60-
61-
// attribute("name", value) // set an attribute on the request
62-
// attribute("name") // get an attribute on the request
63-
// attributeOrCompute("name", ctx -> {}) // get an attribute or compute it based on the context if absent
64-
// attributeMap() // map of all attributes on the request
29+
// GetParam returns the value of the first Param which key matches the given name.
30+
// If no matching Param is found, an empty string is returned.
31+
func (ctx *Context) GetParam(name string) string {
32+
for i := 0; i < ctx.paramCount; i++ {
33+
if ctx.paramNames[i] == name {
34+
return ctx.paramValues[i]
35+
}
36+
}
37+
return ""
38+
}
6539

66-
// contentLength() // content length of the request body
67-
// contentType() // request content type
40+
// GetParamByIndex get one parameter per index
41+
func (ctx *Context) GetParamByIndex(index int) string {
42+
return ctx.paramValues[index]
43+
}
6844

69-
// isMultipart() // true if the request is multipart
70-
// isMultipartFormData() // true if the request is multipart/formdata
45+
// @TODO: cache
46+
func (ctx *Context) QueryParam(name string, defaultValue ...string) string {
47+
if val := ctx.Request.URL.Query().Get(name); val != "" {
48+
return val
49+
}
50+
for _, v := range defaultValue {
51+
return v
52+
}
53+
return ""
54+
}
7155

72-
// sessionAttribute("name", value) // set a session attribute
73-
// sessionAttribute("name") // get a session attribute
74-
// consumeSessionAttribute("name") // get a session attribute, and set value to null
75-
// cachedSessionAttribute("name", value) // set a session attribute, and cache the value as a request attribute
76-
// cachedSessionAttribute("name") // get a session attribute, and cache the value as a request attribute
77-
// cachedSessionAttributeOrCompute(...) // same as above, but compute and set if value is absent
78-
// sessionAttributeMap() // map of all session attributes
79-
// cookieMap() // map of all request cookies
56+
func (ctx *Context) QueryParamInt(name string, defaultValue ...int) int {
57+
str := ctx.QueryParam(name, "0")
58+
if str == "" {
59+
for _, v := range defaultValue {
60+
return v
61+
}
62+
return 0
63+
}
64+
val, err := strconv.Atoi(str)
65+
if err != nil {
66+
return 0
67+
}
68+
return val
69+
}
8070

8171
// Host host as string
8272
func (ctx *Context) Host() string {
@@ -118,10 +108,6 @@ func (ctx *Context) GetCookie(name string) *http.Cookie {
118108
return nil
119109
}
120110

121-
// header("name") // request header by name (can be used with Header.HEADERNAME)
122-
// headerAsClass("name", clazz) // request header by name, as validator typed as specified class
123-
// headerMap() // map of all request headers
124-
125111
// GetHeader gets the first value associated with the given key. If there are no values associated with the key,
126112
// GetHeader returns "".
127113
// It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes

context_response.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,30 @@ func (ctx *Context) Json(v any) {
2222
}
2323
}
2424

25+
// WriteStarted returns true if the ctx.Writer.Write or ctx.Writer.WriteHeader method was called
26+
func (ctx *Context) WriteStarted() bool {
27+
if w, ok := ctx.Writer.(*ResponseWriterSpy); ok {
28+
return w.writeStarted
29+
}
30+
return true
31+
}
32+
33+
// WriteCalled returns true if the ctx.Writer.Write method was called
34+
func (ctx *Context) WriteCalled() bool {
35+
if w, ok := ctx.Writer.(*ResponseWriterSpy); ok {
36+
return w.writeCalled
37+
}
38+
return true
39+
}
40+
41+
// WriteCalled returns true if the ctx.Writer.WriteHeader method was called
42+
func (ctx *Context) WriteHeaderCalled() bool {
43+
if w, ok := ctx.Writer.(*ResponseWriterSpy); ok {
44+
return w.writeHeaderCalled
45+
}
46+
return true
47+
}
48+
2549
// ServeContent replies to the request using the content in the
2650
// provided. The main benefit of ServeContent over io.Copy
2751
// is that it handles Range requests properly, sets the MIME type, and

crypto/crypto.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package crypto
2+
3+
type Crypto interface {
4+
Decrypt(secret []byte, encrypted []byte, aad []byte) (plain []byte, err error)
5+
Encrypt(secret []byte, data []byte, aad []byte) (encrypted []byte, err error)
6+
KeyGenerate(secret []byte, salt []byte, iterations int, length int, digest string) []byte
7+
MessageDecrypt(secret []byte, encoded []byte, aad []byte) (content []byte, err error)
8+
MessageEncrypt(secret []byte, content []byte, aad []byte) (encoded string, err error)
9+
MessageSign(secret []byte, message []byte, digest string) string
10+
MessageVerify(secret []byte, signed []byte) (decoded []byte, err error)
11+
}

crypto_keyring.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package chain
22

33
import (
4+
"log/slog"
5+
46
"github.com/nidorx/chain/crypto"
5-
"github.com/rs/zerolog/log"
67
)
78

89
// NewKeyring starts a Keyring that will be updated whenever SecretKeySync() is invoked
@@ -27,7 +28,7 @@ func NewKeyring(salt string, iterations int, length int, digest string) *crypto.
2728
SecretKeySync(func(secretKeyBase string) {
2829
key := crypt.KeyGenerate([]byte(secretKeyBase), []byte(salt), iterations, length, digest)
2930
if err := k.AddKey(key); err != nil {
30-
log.Error().Err(err).Msg(_l("[chain.keyring] error deriving key from SecretKeyBase"))
31+
slog.Error("[chain.keyring] error deriving key from SecretKeyBase", slog.Any("error", err))
3132
return
3233
}
3334
})

crypto_shortcuts.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,60 +3,60 @@ package chain
33
import "github.com/nidorx/chain/crypto"
44

55
var (
6-
crypt = &cryptoShortcuts{}
7-
msgEncryptor = crypto.MessageEncryptor{}
6+
crypt = &cryptoImpl{}
87
msgVerifier = crypto.MessageVerifier{}
8+
msgEncryptor = crypto.MessageEncryptor{}
99
keyGenerator = crypto.KeyGenerator{}
1010
)
1111

1212
// Crypto get the reference to a structure that has shortcut to all encryption related functions
13-
func Crypto() *cryptoShortcuts {
13+
func Crypto() crypto.Crypto {
1414
return crypt
1515
}
1616

17-
type cryptoShortcuts struct{}
17+
type cryptoImpl struct{}
1818

1919
// Encrypt is used to encrypt a data with a given key.
20-
func (c *cryptoShortcuts) Encrypt(secret []byte, data []byte, aad []byte) (encrypted []byte, err error) {
20+
func (c *cryptoImpl) Encrypt(secret []byte, data []byte, aad []byte) (encrypted []byte, err error) {
2121
return crypto.Encrypt(secret, data, aad)
2222
}
2323

2424
// Decrypt is used to decrypt a message with a given key, and verify it's contents.
25-
func (c *cryptoShortcuts) Decrypt(secret []byte, encrypted []byte, aad []byte) (plain []byte, err error) {
25+
func (c *cryptoImpl) Decrypt(secret []byte, encrypted []byte, aad []byte) (plain []byte, err error) {
2626
return crypto.Decrypt(secret, encrypted, aad)
2727
}
2828

2929
// KeyGenerate Returns a derived key suitable for use.
3030
//
3131
// See crypto.KeyGenerator.Generate()
32-
func (c *cryptoShortcuts) KeyGenerate(secret []byte, salt []byte, iterations int, length int, digest string) []byte {
32+
func (c *cryptoImpl) KeyGenerate(secret []byte, salt []byte, iterations int, length int, digest string) []byte {
3333
return keyGenerator.Generate(secret, salt, iterations, length, digest)
3434
}
3535

3636
// MessageSign generates a signed message for the provided value.
3737
//
3838
// See crypto.MessageVerifier.Sign()
39-
func (c *cryptoShortcuts) MessageSign(secret []byte, message []byte, digest string) string {
39+
func (c *cryptoImpl) MessageSign(secret []byte, message []byte, digest string) string {
4040
return msgVerifier.Sign(secret, message, digest)
4141
}
4242

4343
// MessageVerify decodes and verifies the encoded binary was not tampered with.
4444
//
4545
// See crypto.MessageVerifier.Verify()
46-
func (c *cryptoShortcuts) MessageVerify(secret []byte, signed []byte) (decoded []byte, err error) {
46+
func (c *cryptoImpl) MessageVerify(secret []byte, signed []byte) (decoded []byte, err error) {
4747
return msgVerifier.Verify(secret, signed)
4848
}
4949

5050
// MessageEncrypt encrypts and authenticates a message using AES128-GCM mode.
5151
//
5252
// See crypto.MessageEncryptor.Encrypt()
53-
func (c *cryptoShortcuts) MessageEncrypt(secret []byte, content []byte, aad []byte) (encoded string, err error) {
53+
func (c *cryptoImpl) MessageEncrypt(secret []byte, content []byte, aad []byte) (encoded string, err error) {
5454
return msgEncryptor.Encrypt(secret, content, aad)
5555
}
5656

5757
// MessageDecrypt decrypt a message using authenticated encryption.
5858
//
5959
// See crypto.MessageEncryptor.Decrypt()
60-
func (c *cryptoShortcuts) MessageDecrypt(secret []byte, encoded []byte, aad []byte) (content []byte, err error) {
60+
func (c *cryptoImpl) MessageDecrypt(secret []byte, encoded []byte, aad []byte) (content []byte, err error) {
6161
return msgEncryptor.Decrypt(secret, encoded, aad)
6262
}

0 commit comments

Comments
 (0)