在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官方文档或社区教程。