Add tech_docs/go_getting_started.md

This commit is contained in:
2024-06-18 05:00:19 +00:00
parent c3c816edc2
commit e8da39e26b

View File

@@ -0,0 +1,258 @@
Here's a comprehensive guide to using some essential Go packages for interacting with the operating system and handling various system-level tasks.
## Go Syscall Package
### Overview
The `syscall` package in Go provides an interface for low-level system calls. It's part of the Go standard library but has been somewhat deprecated in favor of `golang.org/x/sys/unix`. However, understanding `syscall` is still beneficial for legacy code or very low-level operations.
### Common Functions
- **syscall.Syscall**: Calls a system service by its index.
- **syscall.ForkExec**: Runs a new process with forks and execs.
- **syscall.Getpid**: Returns the process ID of the calling process.
### Example
```go
package main
import (
"fmt"
"syscall"
"unsafe"
)
func main() {
buf := make([]byte, 64)
_, _, err := syscall.Syscall(syscall.SYS_GETHOSTNAME, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0)
if err != 0 {
fmt.Println("Error getting hostname:", err)
return
}
fmt.Println("Hostname:", string(buf))
}
```
## Go os/exec Package
### Overview
The `os/exec` package runs external commands and interacts with them.
### Common Functions
- **exec.Command**: Creates a new command to run.
- **cmd.Run**: Runs the command and waits for it to finish.
- **cmd.Output**: Runs the command and returns its standard output.
### Example
```go
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-lah")
out, err := cmd.Output()
if err != nil {
fmt.Println("Error running command:", err)
return
}
fmt.Println(string(out))
}
```
## Go os/signal Package
### Overview
The `os/signal` package allows for handling of Unix signals.
### Common Functions
- **signal.Notify**: Registers the given channel to receive notifications of specified signals.
- **signal.Stop**: Stops the given channel from receiving notifications.
### Example
```go
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println("Received signal:", sig)
os.Exit(0)
}()
fmt.Println("Press Ctrl+C to exit")
select {}
}
```
## Go os Package
### Overview
The `os` package provides a platform-independent interface to operating system functionality.
### Common Functions
- **os.Open**: Opens a file for reading.
- **os.Create**: Creates a new file.
- **os.Remove**: Removes a file or directory.
- **os.Getenv**: Retrieves the value of an environment variable.
### Example
```go
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("test.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
file.WriteString("Hello, Go!")
fmt.Println("File created and written to successfully.")
value := os.Getenv("HOME")
fmt.Println("HOME environment variable:", value)
}
```
## Go net Package
### Overview
The `net` package provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
### Common Functions
- **net.Dial**: Connects to a network address.
- **net.Listen**: Listens for network connections.
- **net.Accept**: Accepts network connections on a listener.
### Example
```go
package main
import (
"fmt"
"net"
)
func main() {
l, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer l.Close()
fmt.Println("Listening on :8080")
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading:", err)
return
}
fmt.Println("Received message:", string(buf[:n]))
conn.Write([]byte("Message received"))
conn.Close()
}
```
## Go unix Package
### Overview
The `golang.org/x/sys/unix` package provides a more comprehensive interface for Unix system calls compared to the `syscall` package.
### Common Functions
- **unix.Socket**: Creates an endpoint for communication.
- **unix.Bind**: Binds a name to a socket.
- **unix.Listen**: Listens for connections on a socket.
- **unix.Accept**: Accepts a connection on a socket.
### Example
```go
package main
import (
"fmt"
"golang.org/x/sys/unix"
"os"
"syscall"
)
func main() {
socketPath := "/tmp/unix.sock"
syscall.Unlink(socketPath)
fd, err := unix.Socket(unix.AF_UNIX, unix.SOCK_STREAM, 0)
if err != nil {
fmt.Println("Error creating socket:", err)
return
}
defer unix.Close(fd)
addr := unix.SockaddrUnix{Name: socketPath}
if err := unix.Bind(fd, &addr); err != nil {
fmt.Println("Error binding socket:", err)
return
}
if err := unix.Listen(fd, 5); err != nil {
fmt.Println("Error listening on socket:", err)
return
}
fmt.Println("Server listening on", socketPath)
nfd, _, err := unix.Accept(fd)
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
defer unix.Close(nfd)
buf := make([]byte, 1024)
n, err := unix.Read(nfd, buf)
if err != nil {
fmt.Println("Error reading from connection:", err)
return
}
fmt.Println("Received message:", string(buf[:n]))
unix.Write(nfd, []byte("Hello from server"))
os.Remove(socketPath)
}
```
### Resources
1. **[Go Syscall Package Documentation](https://pkg.go.dev/syscall)**
2. **[Go os/exec Package Documentation](https://pkg.go.dev/os/exec)**
3. **[Go os/signal Package Documentation](https://pkg.go.dev/os/signal)**
4. **[Go os Package Documentation](https://pkg.go.dev/os)**
5. **[Go net Package Documentation](https://pkg.go.dev/net)**
6. **[Go unix Package Documentation](https://pkg.go.dev/golang.org/x/sys/unix)**
These guides should help you get started with each package and provide a solid foundation for building more complex Go applications that interact with the operating system and network.