在CentOS上配置Golang服务器环境,可以按照以下步骤进行:
sudo dnf install golang -y
sudo yum install golang -y
/usr/local
目录下。sudo tar -C /usr/local -xzf go1.20.3.linux-amd64.tar.gz
/etc/profile
或~/.bashrc
文件:sudo vim /etc/profile
export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
source /etc/profile
go version
mkdir -p $GOPATH/src/myapp
cd $GOPATH/src/myapp
main.go
):package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("Starting server at port 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Could not start server: %s", err)
}
}
go build main.go
./main
http://localhost:8080
以上步骤将帮助你在CentOS上成功安装和配置Golang环境,并运行一个简单的Web服务器。