Golang : Issue HTTP commands to server and port example
Problem :
You want to issue or write HTTP command to a connection created by net.DialTCP()
function. How to do that?
Solution :
The net.Conn
type connection returned by net.DialTCP()
function has Write method. Use the Write method to issue HTTP command.
For example :
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s hostname:port_number \n", os.Args[0])
os.Exit(1)
}
serviceAndPort := os.Args[1]
fmt.Println("Service : ", serviceAndPort)
tcpAddr, err := net.ResolveTCPAddr("tcp4", serviceAndPort)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
defer conn.Close()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// issue the HTTP command
nBytes, err := conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Written %v bytes\n", nBytes)
result, err := ioutil.ReadAll(conn)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(result))
}
References :
http://golang.org/pkg/net/#Conn
http://papa.det.uvigo.es/~theiere/cursos/Curso_WWW/codes.html
https://socketloop.com/tutorials/golang-get-curl-i-or-head-data-from-url-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.4k Golang : HTTP response JSON encoded data
+17.6k Golang : How to make a file read only and set it to writable again?
+8.9k Golang : Build and compile multiple source files
+5.9k PageSpeed : Clear or flush cache on web server
+19.8k Golang : How to run your code only once with sync.Once object
+16.1k Golang : convert string or integer to big.Int type
+29.1k Golang : missing Git command
+30.2k Get client IP Address in Go
+6.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+11.6k Golang : How to detect a server/machine network interface capabilities?
+3.5k Java : Get FX sentiment from website example
+4.8k JQuery : Calling a function inside Jquery(document) block