Skip to content

Instantly share code, notes, and snippets.

@Deriul
Last active August 17, 2020 20:25
Show Gist options
  • Select an option

  • Save Deriul/f49a94d48030193f5451ed68de3c6ba6 to your computer and use it in GitHub Desktop.

Select an option

Save Deriul/f49a94d48030193f5451ed68de3c6ba6 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"time"
)
var uname string = "admin"
var pwd string = "adm!nd42"
var addr string = "https://10.10.10.10"
type Client struct {
HostURL string
HTTPClient *http.Client
Token string
}
func main() {
c, _ := NewClient(&addr, &uname, &pwd)
subnet, _ := c.GetSubnet("1")
fmt.Println(string([]byte(subnet)))
}
func NewClient(host, username, password *string) (*Client, error) {
c := Client{
HTTPClient: &http.Client{Timeout: 10 * time.Second},
HostURL: addr,
}
if host != nil {
c.HostURL = *host
}
if (username != nil) && (password != nil) {
c.Token = "Basic " + base64.StdEncoding.EncodeToString([]byte(*username+":"+*password))
}
return &c, nil
}
func (c *Client) GetSubnet(ID string) ([]byte, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/1.0/subnets/%s/", c.HostURL, ID), nil)
if err != nil {
return nil, err
}
body, err := c.doRequest(req) // wrap HTTPClient.Do and adds auth, returns []byte with body
if err != nil {
return nil, err
}
return body, nil
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) { //returns []byte with body inside
req.Header.Set("Authorization", c.Token)
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}
return body, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment