Skip to content
Snippets Groups Projects
http.go 1.12 KiB
Newer Older
  • Learn to ignore specific revisions
  • Manuel Kieweg's avatar
    Manuel Kieweg committed
    package cli
    
    import (
    	"fmt"
    	log "github.com/sirupsen/logrus"
    
    	"github.com/spf13/viper"
    
    Manuel Kieweg's avatar
    Manuel Kieweg committed
    	"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))
    		}
    
    Manuel Kieweg's avatar
    Manuel Kieweg committed
    	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
    }