php editor Zimo introduces you a method to connect to the Golang code of the FTP server by using a proxy. In some cases, we may need to use a proxy server when accessing the FTP server in order to increase security or resolve network restrictions. Golang is a powerful programming language with easy-to-use network libraries, so we can implement this feature easily. Next, we will use a simple sample code to demonstrate how to use Golang to connect to an FTP server through a proxy.
Question content
I need to connect to ftp server through proxy and download files from Golang code. I have implemented simple client:
<code>package main import ( "bufio" "fmt" "github.com/jlaffaye/ftp" "io" "log" "net" "net/http" "os" "strings" "time" ) var targetAddr = "ftp.dlptest.com" var proxyAddr = "146.19.106.109:3128" var user = "dlpuser" var pass = "rNrKYTX9g7z3RgJRmxWuGHbeu" var path = "/xxx.txt" func connectViaProxy(network, address string) (net.Conn, error) { parts := strings.Split(address, ":") addr := fmt.Sprintf("%s:%s", targetAddr, parts[1]) proxyConn, err := net.Dial(network, proxyAddr) if err != nil { return nil, err } req, err := http.NewRequest(http.MethodConnect, "http://"+addr, nil) if err != nil { proxyConn.Close() return nil, err } req.Header.Set("Accept", "*/*") req.Header.Set("User-Agent", "curl/8.1.2") req.Header.Set("Host", targetAddr+":21") err = req.Write(proxyConn) if err != nil { return nil, err } resp, err := http.ReadResponse(bufio.NewReader(proxyConn), req) if err != nil { proxyConn.Close() return nil, err } if resp.StatusCode != 200 { x, _ := io.ReadAll(resp.Body) fmt.Println(string(x)) proxyConn.Close() return nil, fmt.Errorf("non-200 status code received from proxy: %v", resp.Status) } return proxyConn, nil } func main() { c, err := ftp.Dial(targetAddr+":21", ftp.DialWithTimeout(5*time.Second), ftp.DialWithDebugOutput(os.Stdin), ftp.DialWithDialFunc(connectViaProxy), ) if err != nil { log.Fatal(err) } err = c.Login(user, pass) if err != nil { log.Fatal(err) } if r, err := c.Retr(path); err != nil { fmt.Println(err, ":<") } else { if reader, err := io.ReadAll(r); err != nil { fmt.Println(err, ":(") } else { fmt.Println(string(reader)) } } if err = c.Quit(); err != nil { log.Fatal(err) } } </code>
Unfortunately, I receive a 403 Forbidden when trying to connect. Normally I would assume this is a server limitation, but it works perfectly fine via curl:
curl -vvv -x 146.19.106.109:3128 -u dlpuser:rNrKYTX9g7z3RgJRmxWuGHbeu ftp://ftp.dlptest.com/xxx.txt
Does anyone know why this happens? As far as I know, curl also uses http CONNECT under the hood, so I'm wondering what I'm missing.
PS Don't worry about the credentials in the code - these are exposed for network testing
Workaround
FTP over the HTTP proxy is not done with a CONNECT request. Instead, the proxy is instructed to obtain the ftp://...
URL using a normal GET request. This is also what curl is doing. In Go, it can be done like this (error handling omitted for simplicity):
// create the TCP connection to the proxy conn, err := net.Dial("tcp", "146.19.106.109:3128") // create the request with the ftp:// URL req, err := http.NewRequest(http.MethodGet, "ftp://ftp.dlptest.com/xxx.txt", nil) req.SetBasicAuth("dlpuser","rNrKYTX9g7z3RgJRmxWuGHbeu") // don't use req.Write but req.WriteProxy, since the request line must // contain the full URL and not only the path err = req.WriteProxy(conn) // read response resp, err := http.ReadResponse(bufio.NewReader(conn), req) body, _ := io.ReadAll(resp.Body)
The above is the detailed content of Connect to ftp through proxy from golang. For more information, please follow other related articles on the PHP Chinese website!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
