mirror of
https://github.com/go-i2p/go-meta-listener.git
synced 2025-07-04 06:35:27 -04:00
Add Host and X-Forwarded-X headers if there's an HTTP connection involved
This commit is contained in:
51
mirror/header.go
Normal file
51
mirror/header.go
Normal file
@ -0,0 +1,51 @@
|
||||
package mirror
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// AddHeaders adds headers to the connection.
|
||||
// It takes a net.Conn and a map of headers as input.
|
||||
// It only adds headers if the connection is an HTTP connection.
|
||||
// It returns a net.Conn with the headers added.
|
||||
func AddHeaders(conn net.Conn, headers map[string]string) net.Conn {
|
||||
// read a request from the connection
|
||||
// if the request is an HTTP request, add the headers
|
||||
// if the request is not an HTTP request, return the connection as is
|
||||
req, err := http.ReadRequest(bufio.NewReader(conn))
|
||||
if err != nil {
|
||||
return conn
|
||||
}
|
||||
for key, value := range headers {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
// write the request back to the connection
|
||||
if err := req.Write(conn); err != nil {
|
||||
return conn
|
||||
}
|
||||
// return the connection with the headers added
|
||||
return conn
|
||||
}
|
||||
|
||||
// Accept accepts a connection from the listener.
|
||||
// It takes a net.Listener as input and returns a net.Conn with the headers added.
|
||||
// It is used to accept connections from the meta listener and add headers to them.
|
||||
func (ml *Mirror) Accept() (net.Conn, error) {
|
||||
// Accept a connection from the listener
|
||||
conn, err := ml.MetaListener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
host := map[string]string{
|
||||
"Host": ml.MetaListener.Addr().String(),
|
||||
"X-Forwarded-For": conn.RemoteAddr().String(),
|
||||
"X-Forwarded-Proto": "http",
|
||||
}
|
||||
// Add headers to the connection
|
||||
conn = AddHeaders(conn, host)
|
||||
|
||||
return conn, nil
|
||||
}
|
Reference in New Issue
Block a user