在Debian中進行Go語言網絡編程,可按以下步驟操作:
sudo apt update && sudo apt install golang-go
,安裝后用go version
驗證。~/.bashrc
,添加:export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
運行source ~/.bashrc
生效。package main
import (
"bufio"
"fmt"
"net"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, _ := reader.ReadString('\n')
fmt.Print("Received: ", message)
conn.Write([]byte("Server received: " + message))
}
}
func main() {
listener, _ := net.Listen("tcp", ":8080")
defer listener.Close()
fmt.Println("Listening on :8080")
for {
conn, _ := listener.Accept()
go handleConnection(conn)
}
}
保存為main.go
,運行go run main.go
啟動服務器,用telnet localhost 8080
測試。package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, HTTP!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8081", nil)
}
運行后可通過瀏覽器訪問http://localhost:8081
。go get
安裝,如Redis客戶端redigo
:sudo apt install golang-github-gomodule-redigo-dev
,或直接在代碼中引入import "github.com/gomodule/redigo/redis"
。更多協議(如UDP、WebSocket)可參考Go官方文檔或社區教程。