Newer
Older
package cli
import (
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
)
const apiRoot = "/api?"
var builder *strings.Builder
func init() {
builder = &strings.Builder{}
}
func HttpGet(apiEndpoint, f string, args ...string) error {
for _, p := range args {
builder.WriteString("&")
builder.WriteString(p)
}
resp, err := http.Get(apiEndpoint + apiRoot + "q=" + f + builder.String())
if err != nil {
return err
}
builder.Reset()
switch resp.StatusCode {
case http.StatusOK:
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if f == "init" {
pnd := string(bytes[:36])
sbi := string(bytes[36:])
viper.Set("CLI_PND", pnd)
viper.Set("CLI_SBI", sbi)
return viper.WriteConfig()
} else {
fmt.Println(string(bytes))
}
case http.StatusCreated:
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(string(bytes))
default:
log.WithFields(log.Fields{
"status code": resp.StatusCode,
}).Error("operation unsuccessful")
}
return nil
}