<p>I'm writing a small terminal utility that provides definition, translation and other actions and I have to use many api, also I need a way to replace the apis if needed, and while trying to write tests for this I feel I got it all wrong.</p>
<p>Gist: <a href="https://gist.github.com/taosx/4b615381456561da797ac55fd17e981b" rel="nofollow">https://gist.github.com/taosx/4b615381456561da797ac55fd17e981b</a></p>
<pre><code>package main
import (
"fmt"
"log"
"net/url"
"strings"
"github.com/valyala/fasthttp"
)
// API is our main struct, it helps create our url in any way we like and returns a string
// It is a must to provide the url string like this: api := API{url: "http://api.baseurl.com"}
type API struct {
api *url.URL
url string
}
func (a *API) String() interface{} {
return a.api
}
// Create function fills our url.URL type by using the url in struct API
func (a *API) Create() *API {
api, err := url.Parse(a.url)
if err != nil {
log.Fatal("[ERR] ", err)
}
a.api = api
return a
}
// Suffix function adds our path to our api
func (a *API) Suffix(suffixes ...string) *API {
if len(suffixes) < 1 {
fmt.Println("Can't leave suffix empty")
return a
}
a.api.Path += strings.Join(suffixes, "/")
return a
}
// Query function adds our queries to our api
func (a *API) Query(query url.Values) *API {
if len(query) < 1 {
fmt.Println("Can't leave query empty")
return a
}
q := a.api.Query()
for k, v := range query {
if len(v) > 1 {
v := strings.Join(v, ",")
q.Add(k, v)
} else {
q.Add(k, v[0])
}
}
encQuery := q.Encode()
escQuery, _ := url.QueryUnescape(encQuery)
a.api.RawQuery += escQuery
return a
}
// Get makes a request to the url crafted and returns: <status code>, <response/body>, <error(if any or nil otherwise)>
func (a *API) Get() (int, []byte, error) {
urlstr := a.api.String()
saved := []byte{}
status, body, err := fasthttp.Get(saved, urlstr)
if err != nil {
fmt.Println("Error:", err)
return status, nil, err
}
return status, body, err
}
</code></pre>
<hr/>**评论:**<br/><br/>sethammons: <pre><p>do you mean here?</p>
<pre><code>func (a *API) String() interface{} {
return a.api
}
</code></pre>
<p>I wouldn't. I would <code>func (a *API) String() string</code> because that is typically what a <code>String()</code> method does. If you want to have an accessor for getting at <code>a.api</code>, you could have <code>func (a *API) URL() *url.URL</code>. If you find that you need something that is not specific (ie, you wont always return <code>*url.URL</code>, then use an interface. See <a href="http://go-book.appspot.com/interfaces.html" rel="nofollow">http://go-book.appspot.com/interfaces.html</a> for an example of that. Cheers!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传