Fragment Description:



A TCP GetHeadInfo example.
Using net.ResolveTCPAddr sign:
func ResolveTCPAddr(net, addr string) (*TCPAddr, os.Error) To be noted:
In this example, we read essentially a single response from the server.
This will be terminated by end-of-file on the connection.
However, it may consist of several TCP packets, so we need to keep reading till the end of file.
The io/ioutil function ReadAll will look after these issues and return the complete response.
(Thanks to Roger Peppe on the golang-nuts mailing list.
.
By Jan Newmarch (see his excellent ebook:
https://jan.newmarch.name/go/ )

tcpGetHeadInfo

Last update, on 2015, Fri 9 Oct, 16:15:41

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "io/ioutil"
    "net"
    "os"
)

func main() {
    // if len(os.Args) != 2 {
    // fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
    // os.Exit(1)
    // }
    // service := os.Args[1]
    service := "www.google.com:80"
    tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
    checkError(err)
    conn, err := net.DialTCP("tcp", nil, tcpAddr)
    checkError(err)
    _, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
    checkError(err)
    // reading to the EOF, is the added value here of "ioutil.ReadAll"
    result, err := ioutil.ReadAll(conn)
    checkError(err)
    fmt.Println(string(result))
    os.Exit(0)
}
func checkError(err error) {
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
        os.Exit(1)
    }
}

/* Expected Output:
HTTP/1.0 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.uk/?gfe_rd=cr&ei=-iH7VYLqIYTj8wf75J6ADg
Content-Length: 261
Date: Thu, 17 Sep 2015 20:26:34 GMT
Server: GFE/2.0
*/



Comments