The Client object

To send a request to a server and get a reply, the convenience object Client is the easiest way. This object can manage multiple requests and will look after issues such as whether the server keeps the TCP connection alive, and so on.

This is illustrated in the following program

  1. /* ClientGet
  2. */
  3. package main
  4. import (
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "strings"
  10. )
  11. func main() {
  12. if len(os.Args) != 2 {
  13. fmt.Println("Usage: ", os.Args[0], "http://host:port/page")
  14. os.Exit(1)
  15. }
  16. url, err := url.Parse(os.Args[1])
  17. checkError(err)
  18. client := &http.Client{}
  19. request, err := http.NewRequest("GET", url.String(), nil)
  20. // only accept UTF-8
  21. request.Header.Add("Accept-Charset", "UTF-8;q=1, ISO-8859-1;q=0")
  22. checkError(err)
  23. response, err := client.Do(request)
  24. if response.Status != "200 OK" {
  25. fmt.Println(response.Status)
  26. os.Exit(2)
  27. }
  28. chSet := getCharset(response)
  29. fmt.Printf("got charset %s\n", chSet)
  30. if chSet != "UTF-8" {
  31. fmt.Println("Cannot handle", chSet)
  32. os.Exit(4)
  33. }
  34. var buf [512]byte
  35. reader := response.Body
  36. fmt.Println("got body")
  37. for {
  38. n, err := reader.Read(buf[0:])
  39. if err != nil {
  40. os.Exit(0)
  41. }
  42. fmt.Print(string(buf[0:n]))
  43. }
  44. os.Exit(0)
  45. }
  46. func getCharset(response *http.Response) string {
  47. contentType := response.Header.Get("Content-Type")
  48. if contentType == "" {
  49. // guess
  50. return "UTF-8"
  51. }
  52. idx := strings.Index(contentType, "charset:")
  53. if idx == -1 {
  54. // guess
  55. return "UTF-8"
  56. }
  57. return strings.Trim(contentType[idx:], " ")
  58. }
  59. func checkError(err error) {
  60. if err != nil {
  61. fmt.Println("Fatal error ", err.Error())
  62. os.Exit(1)
  63. }
  64. }