twitter_status.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // twitter_status.go
  2. package main
  3. import (
  4. "net/http"
  5. "fmt"
  6. "encoding/xml"
  7. "io/ioutil"
  8. )
  9. /* these structs will house the unmarshalled response.
  10. they should be hierarchically shaped like the XML
  11. but can omit irrelevant data. */
  12. type Status struct {
  13. Text string
  14. }
  15. type User struct {
  16. XMLName xml.Name
  17. Status Status
  18. }
  19. // var user User
  20. func main() {
  21. // perform an HTTP request for the twitter status of user: Googland
  22. resp, _ := http.Get("http://twitter.com/users/Googland.xml")
  23. // initialize the structure of the XML response
  24. user := User{xml.Name{"", "user"}, Status{""}}
  25. // unmarshal the XML into our structures
  26. defer resp.Body.Close()
  27. if body, err := ioutil.ReadAll(resp.Body); err != nil {
  28. fmt.Printf("error: %s", err.Error())
  29. } else {
  30. fmt.Printf("%s ---", body)
  31. xml.Unmarshal(body, &user)
  32. }
  33. fmt.Printf("name: %s ", user.XMLName)
  34. fmt.Printf("status: %s", user.Status.Text)
  35. }
  36. /* Output:
  37. status: Robot cars invade California, on orders from Google: Google has been testing self-driving cars ... http://bit.ly/cbtpUN http://retwt.me/97p<exit code="0" msg="process exited normally"/>
  38. After Go1: no output: name: { user} status:
  39. */