github.com/wtfutil/wtf@v0.43.0/modules/weatherservices/arpansagovau/client.go (about)

     1  package arpansagovau
     2  
     3  import (
     4  	"encoding/xml"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  )
     9  
    10  type Stations struct {
    11  	XMLName  xml.Name `xml:"stations"`
    12  	Text     string   `xml:",chardata"`
    13  	Location []struct {
    14  		Text        string  `xml:",chardata"`
    15  		ID          string  `xml:"id,attr"`
    16  		Name        string  `xml:"name"`        // adl, ali, bri, can, cas, ...
    17  		Index       float32 `xml:"index"`       // 0.0, 0.0, 0.0, 0.0, 0.0, ...
    18  		Time        string  `xml:"time"`        // 7:24 PM, 7:24 PM, 7:54 PM...
    19  		Date        string  `xml:"date"`        // 29/08/2019, 29/08/2019, 2...
    20  		Fulldate    string  `xml:"fulldate"`    // Thursday, 29 August 2019,...
    21  		Utcdatetime string  `xml:"utcdatetime"` // 2019/08/29 09:54, 2019/08...
    22  		Status      string  `xml:"status"`      // ok, ok, ok, ok, ok, ok, o...
    23  	} `xml:"location"`
    24  }
    25  
    26  type location struct {
    27  	name   string
    28  	index  float32
    29  	time   string
    30  	date   string
    31  	status string
    32  }
    33  
    34  func getLocationData(cityname string) (*location, error) {
    35  	var locdata location
    36  	resp, err := apiRequest()
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	stations, err := parseXML(resp.Body)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	for _, city := range stations.Location {
    47  		if city.ID == cityname {
    48  			locdata = location{name: city.ID, index: city.Index, time: city.Time, date: city.Date, status: city.Status}
    49  			break
    50  		}
    51  	}
    52  	return &locdata, err
    53  }
    54  
    55  /* -------------------- Unexported Functions -------------------- */
    56  
    57  func apiRequest() (*http.Response, error) {
    58  	req, err := http.NewRequest("GET", "https://uvdata.arpansa.gov.au/xml/uvvalues.xml", http.NoBody)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  
    63  	httpClient := &http.Client{}
    64  	resp, err := httpClient.Do(req)
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	defer func() { _ = resp.Body.Close() }()
    69  
    70  	if resp.StatusCode != 200 {
    71  		return nil, fmt.Errorf(resp.Status)
    72  	}
    73  
    74  	return resp, nil
    75  }
    76  func parseXML(text io.Reader) (Stations, error) {
    77  	dec := xml.NewDecoder(text)
    78  	dec.Strict = false
    79  
    80  	var v Stations
    81  	err := dec.Decode(&v)
    82  	return v, err
    83  }