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

View File

@ -7,12 +7,6 @@ import (
) )
func main(){ 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:]) argCount := len(os.Args[1:])
var ( var (
@ -32,9 +26,12 @@ func main(){
flag.Usage() flag.Usage()
} }
stations := GetStations("tag=chicago") stations, err := GetStations("tag=chicago")
for station := range(len(stations)) { 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)
} }