json parsing: GO! next up: generate the menu...

This commit is contained in:
Greg Gauthier 2021-03-16 16:42:30 +00:00
parent 3da2da7d4b
commit a06bc91576
2 changed files with 26 additions and 29 deletions

View File

@ -3,7 +3,6 @@ package main
import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
@ -11,21 +10,17 @@ import (
"time"
)
//func BytesToString(b []byte) string {
// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
// sh := reflect.StringHeader{bh.Data, bh.Len}
// return *(*string)(unsafe.Pointer(&sh))
//}
func ResponseToJson(resp io.ReadCloser) interface{} {
var jbody interface{}
err := json.NewDecoder(resp).Decode(&jbody)
if err != nil {
panic(err)
}
return jbody
type stationRecord struct {
Name string `json:"name"`
Codec string `json:"codec"`
Bitrate json.Number `json:"bitrate"`
Countrycode string `json:"countrycode"`
Tags string `json:"tags"`
Url string `json:"url"`
Lastcheck int `json:"lastcheck"`
}
func RandomIP(iplist []net.IP) net.IP {
rand.Seed(time.Now().Unix())
randomIndex := rand.Intn(len(iplist))
@ -49,15 +44,20 @@ func GetApiHost() string {
return apiHost
}
func GetStations(qstring string) interface{} {
func GetStations(qstring string) ([]stationRecord, error){
urlstr := fmt.Sprintf("https://%s/json/stations/search?%s&limit=100000",GetApiHost(),qstring)
resp, err := http.Get(urlstr)
if err != nil {
log.Printf(err.Error())
}
defer resp.Body.Close()
bodyJson := ResponseToJson(resp.Body)
//body, err := io.ReadAll(resp.Body)
//bodyString := bytes.NewBuffer(body).String()
return bodyJson
}
var data []stationRecord
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return data, err
}
return data, err
}

View File

@ -7,12 +7,6 @@ import (
)
func main(){
fmt.Println("Configuration values:")
fmt.Println("api url: ", api())
fmt.Println("player command: ", player())
fmt.Println("player options: ", options())
fmt.Println("maximum menu items: ", maxitems())
argCount := len(os.Args[1:])
var (
@ -32,9 +26,12 @@ func main(){
flag.Usage()
}
stations := GetStations("tag=chicago")
for station := range(len(stations)) {
stations, err := GetStations("tag=chicago")
if err != nil{
fmt.Println(err.Error())
}
for _, station := range stations {
fmt.Printf("\"%s\", %s, %s, %s\n", station.Name, station.Codec, station.Bitrate, station.Url)
}