Skip to content

Instantly share code, notes, and snippets.

@jniltinho
Last active March 12, 2023 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jniltinho/5773e100bff0f693fbd706358f33168c to your computer and use it in GitHub Desktop.
Save jniltinho/5773e100bff0f693fbd706358f33168c to your computer and use it in GitHub Desktop.
Criando um socket para o Postfix com Golang
package main
import (
"fmt"
"net"
"os"
)
func handleConnection(conn net.Conn) {
// Handle incoming connection from Postfix
fmt.Println("Connection accepted:", conn.RemoteAddr())
// Do something with the connection, e.g. read email message
}
func main() {
// Create Unix domain socket
socketFile := "/var/spool/postfix/private/mysocket"
err := os.RemoveAll(socketFile)
if err != nil {
fmt.Println("Error removing existing socket file:", err)
}
listener, err := net.Listen("unix", socketFile)
if err != nil {
fmt.Println("Error creating socket listener:", err)
return
}
defer listener.Close()
// Accept incoming connections
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
//main.cf
//default_transport = mysocket:
//mysocket_unix_path = /var/spool/postfix/private/mysocket
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func handleConnection(conn net.Conn) {
// Handle incoming connection from Postfix
fmt.Println("Connection accepted:", conn.RemoteAddr())
// Create a buffered reader to read incoming data
reader := bufio.NewReader(conn)
messageBuffer := []byte{}
for {
// Read from the connection and add to buffer
chunk := make([]byte, 4096)
n, err := reader.Read(chunk)
if err != nil {
fmt.Println("Error reading from connection:", err)
return
}
messageBuffer = append(messageBuffer, chunk[:n]...)
// Check if we've received the complete message
if n == 0 || messageBuffer[len(messageBuffer)-1] == '\n' {
// We've received the complete message
message := string(messageBuffer)
fmt.Println("Received message:", message)
// Do something with the message, e.g. save to disk
// ...
// Reset the message buffer for the next message
messageBuffer = []byte{}
// If the connection is closed by Postfix, exit the loop
if n == 0 {
break
}
}
}
}
func main() {
// Create Unix domain socket
socketFile := "/var/spool/postfix/private/mysocket"
err := os.RemoveAll(socketFile)
if err != nil {
fmt.Println("Error removing existing socket file:", err)
}
listener, err := net.Listen("unix", socketFile)
if err != nil {
fmt.Println("Error creating socket listener:", err)
return
}
defer listener.Close()
// Accept incoming connections
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment