|
33 | 33 | @[params] |
34 | 34 | pub struct Config { |
35 | 35 | pub mut: |
36 | | - host string = '127.0.0.1' // Redis server host |
37 | | - port u16 = 6379 // Redis server port |
38 | | - version int = 2 // RESP protocol version (default: v2) |
| 36 | + host string = '127.0.0.1' // Redis server host |
| 37 | + port u16 = 6379 // Redis server port |
| 38 | + password string // Redis server password (optional) |
| 39 | + version int = 2 // RESP protocol version (default: v2) |
39 | 40 | } |
40 | 41 |
|
41 | 42 | // connect establishes a connection to a Redis server |
42 | 43 | pub fn connect(config Config) !DB { |
43 | | - conn := net.dial_tcp('${config.host}:${config.port}')! |
44 | | - return DB{ |
45 | | - conn: conn |
| 44 | + mut db := DB{ |
| 45 | + conn: net.dial_tcp('${config.host}:${config.port}')! |
46 | 46 | version: config.version |
47 | 47 | cmd_buf: []u8{cap: cmd_buf_pre_allocate_len} |
48 | 48 | resp_buf: []u8{cap: resp_buf_pre_allocate_len} |
49 | 49 | } |
| 50 | + |
| 51 | + // Authenticate if password is provided |
| 52 | + if config.password.len > 0 { |
| 53 | + db.auth(config.password)! |
| 54 | + } |
| 55 | + |
| 56 | + return db |
50 | 57 | } |
51 | 58 |
|
52 | 59 | // close terminates the connection to Redis server |
53 | 60 | pub fn (mut db DB) close() ! { |
54 | 61 | db.conn.close()! |
55 | 62 | } |
56 | 63 |
|
| 64 | +// auth sends an AUTH command to the server with the given password. |
| 65 | +pub fn (mut db DB) auth(password string) ! { |
| 66 | + resp := db.cmd('AUTH', password)! |
| 67 | + match resp { |
| 68 | + string { |
| 69 | + if resp != 'OK' { |
| 70 | + return error('Authentication failed: ${resp}') |
| 71 | + } |
| 72 | + } |
| 73 | + else { |
| 74 | + return error('Authentication failed: unexpected response type') |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
57 | 79 | // ping sends a PING command to verify server responsiveness |
58 | 80 | pub fn (mut db DB) ping() !string { |
59 | 81 | db.conn.write_string('*1\r\n$4\r\nPING\r\n')! |
|
0 commit comments