add SetOptions method

有了这个方法就可以随时改变配置
This commit is contained in:
taoyu 2018-12-10 19:39:13 +08:00
parent 45125eb015
commit 0bc50ecae2
3 changed files with 38 additions and 16 deletions

View File

@ -4,8 +4,6 @@ import (
"net/http"
"io/ioutil"
"io"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"time"
"bytes"
@ -105,9 +103,8 @@ func parseResp(body []byte) (*Resp, error) {
}
type Client struct {
opts *options
sha256Token string
httpClient *http.Client
opts *options
httpClient *http.Client
}
func (c *Client) request(method, path string, body io.Reader) (resp *Resp, err error) {
@ -115,7 +112,7 @@ func (c *Client) request(method, path string, body io.Reader) (resp *Resp, err e
if err != nil {
return
}
req.Header.Set("X-Judge-Server-Token", c.sha256Token)
req.Header.Set("X-Judge-Server-Token", c.opts.sha256Token)
req.Header.Set("Content-Type", "application/json")
httpResp, err := c.httpClient.Do(req)
@ -162,15 +159,24 @@ func New(endpointURL, token string, timeout time.Duration) *Client {
)
}
func (c *Client) SetOptions(options ...Option) {
originTimeout := c.opts.Timeout
for _, o := range options {
o(c.opts)
}
if c.opts.Timeout != originTimeout {
c.httpClient.Timeout = c.opts.Timeout
}
}
func NewClient(options ...Option) *Client {
opts := DefaultOptions
for _, o := range options {
o(opts)
}
sha256Token := sha256.Sum256([]byte(opts.Token))
return &Client{
opts: opts,
sha256Token: hex.EncodeToString(sha256Token[:]),
opts: opts,
httpClient: &http.Client{
Timeout: opts.Timeout,
},

View File

@ -58,12 +58,21 @@ print(int(s1[0]) + int(s1[1]))
)
func main() {
// 创建一个client。 这句代码等价于 judge.New("http://127.0.0.1:12358", "YOUR_TOKEN_HERE", 0)
client := judge.NewClient(
judge.WithEndpointURL("http://127.0.0.1:12358"),
judge.WithToken("YOUR_TOKEN_HERE"),
judge.WithTimeout(0),
)
// 创建一个client。 这句代码等价于
// 1.
//client := judge.NewClient(
// judge.WithEndpointURL("http://127.0.0.1:12358"),
// judge.WithToken("YOUR_TOKEN_HERE"),
// judge.WithTimeout(0),
//)
// 2.
// client := judge.New("http://127.0.0.1:12358", "YOUR_TOKEN_HERE", 0)
// 3.
client := judge.NewClient(judge.WithTimeout(0))
client.SetOptions(judge.WithEndpointURL("http://127.0.0.1:12358"), judge.WithToken("YOUR_TOKEN_HERE"))
fmt.Println("ping:")
resp, err := client.Ping()

View File

@ -1,11 +1,16 @@
package judge
import "time"
import (
"time"
"crypto/sha256"
"encoding/hex"
)
type options struct {
// scheme://host:port .
EndpointURL string
Token string
sha256Token string
// 请求超时时间
// 如果 Timeout 为 0那么意味着不会超时
Timeout time.Duration
@ -28,6 +33,8 @@ func WithEndpointURL(u string) Option {
func WithToken(token string) Option {
return func(o *options) {
o.Token = token
sha256Token := sha256.Sum256([]byte(token))
o.sha256Token = hex.EncodeToString(sha256Token[:])
}
}