Skip to content

Instantly share code, notes, and snippets.

@taosx
Last active April 21, 2016 15:29
Show Gist options
  • Save taosx/4b615381456561da797ac55fd17e981b to your computer and use it in GitHub Desktop.
Save taosx/4b615381456561da797ac55fd17e981b to your computer and use it in GitHub Desktop.
Make it easy to add of new apis or replace existing ones
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment