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
+6.8k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+9.8k Golang : Text file editor (accept input from screen and save to file)
+24k Golang : GORM read from database example
+11.4k Golang : Verify Linux user password again before executing a program example
+33.2k Golang : How to check if slice or array is empty?
+39k Golang : Remove dashes(or any character) from string
+24k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+13.1k Golang : reCAPTCHA example
+8.7k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+28.9k Golang : JQuery AJAX post data to server and send data back to client example
+30.9k Golang : How to convert(cast) string to IP address?
+6.5k Golang : How to solve "too many .rsrc sections" error?