Home  >  Article  >  Backend Development  >  Make http requests through tcp connection in go

Make http requests through tcp connection in go

王林
王林forward
2024-02-09 12:20:09801browse

Make http requests through tcp connection in go

php editor Strawberry will introduce to you how to make an HTTP request through a TCP connection in the Go language. In web development, we often need to communicate with other servers and get data or send requests. Go language provides a rich standard library, which contains functions for creating TCP connections and sending HTTP requests. By mastering these skills, we can easily implement communication with other servers in the Go language to obtain and send data. Next, let’s dive into this interesting topic!

Question content

package main

import (
    "crypto/tls"
    "fmt"
)

func main() {
    conf := &tls.Config{}
    conn, _ := tls.Dial("tcp", "www.google.com:443", conf)
    data := []byte("GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n")
    conn.Write(data)
    buf := make([]byte, 5000)
    conn.Read(buf)
    fmt.Println(string(buf[:]))
}

I tried to make an http request through raw tcp connection data but received an error response of 400 bad request, what is the problem.

Solution

There is an error in the data.

http1.1 should be http/1.1.

I wanted to share how I discovered this spelling error in the hope it helps others.

When I want to solve a problem that I'm not very familiar with, the first thing I do is find out what it looks like when it works. I've used nc before, so I'll try it first.

This is an example from the nc man page:

$ printf "get / http/1.0\r\n\r\n" | nc host.example.com 80

So I first replaced host.example.com with www.google.com :

$ printf "get / http/1.0\r\n\r\n" | nc www.google.com 80

It works!

Then replace http/1.0 with http/1.1. Still works!

Then add the host header:

$ printf "get / http/1.1\r\nhost: www.google.com\r\n\r\n" | nc www.google.com 80

efficient!

Then copy the string in the question:

$ printf "GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n" | nc www.google.com 80

got 400 Bad Request this time.

This is a big step forward! There was a problem with the request. Typing errors are easy to spot by comparing the two requests.

Finally, fix the typo in the original demo and run the demo to verify that the issue has been resolved. Finish!

Thank you for reading!

The above is the detailed content of Make http requests through tcp connection in go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete