Bài tập: Functional options có kiểm tra lỗi
Cài đặt pattern functional options cho constructor của một HTTP client giả định. Driver đã khai báo sẵn:
type Client struct {
BaseURL string
Timeout time.Duration
Retries int
UserAgent string
}
type Option func(*Client) errorViết:
func WithTimeout(d time.Duration) Option // d <= 0 -> lỗi
func WithRetries(n int) Option // n < 0 -> lỗi (0 là hợp lệ: không thử lại)
func WithUserAgent(ua string) Option // chuỗi rỗng -> lỗi
func NewClient(baseURL string, opts ...Option) (*Client, error)NewClient:
baseURLrỗng →(nil, lỗi);- giá trị mặc định:
Timeout = 10s,Retries = 3,UserAgent = "gocourse/1.0"; - áp dụng
optstheo thứ tự (option sau ghi đè option trước); - một option trả lỗi →
(nil, lỗi đó)— không bao giờ trả về client cấu hình dở.
Mỗi dòng input là baseURL (dấu - nghĩa là chuỗi rỗng) theo sau là các option dạng timeout=5s, retries=1, ua=bot/2 (ua= là user agent rỗng). Driver in ok base=... timeout=... retries=... ua=... hoặc error.
NOTE
Bạn chỉ viết phần code trong khung soạn thảo — package main, kiểu Client, Option và hàm main đọc input/in kết quả đã có sẵn. Các package đã import: bufio, errors, fmt, os, strconv, strings, time. Không thêm import khác.
Examples
Example 1
Input
https://api.vn https://api.vn timeout=5s retries=1 ua=bot/2
Expected output
ok base=https://api.vn timeout=10s retries=3 ua=gocourse/1.0 ok base=https://api.vn timeout=5s retries=1 ua=bot/2
Example 2
Input
https://api.vn timeout=0s - https://api.vn ua=
Expected output
error error error
4 hidden tests · Limit 2 s · 256 MB
// WithTimeout đặt Timeout; d <= 0 -> lỗi.
func WithTimeout(d time.Duration) Option {
// TODO
return nil
}
// WithRetries đặt số lần thử lại; n < 0 -> lỗi (0 hợp lệ).
func WithRetries(n int) Option {
// TODO
return nil
}
// WithUserAgent đặt UserAgent; chuỗi rỗng -> lỗi.
func WithUserAgent(ua string) Option {
// TODO
return nil
}
// NewClient tạo Client với mặc định Timeout = 10s, Retries = 3, UserAgent = "gocourse/1.0",
// rồi áp dụng opts theo thứ tự. baseURL rỗng hoặc option lỗi -> (nil, err).
func NewClient(baseURL string, opts ...Option) (*Client, error) {
// TODO
return nil, nil
}
Comments