ubuntu

golang在ubuntu上的运行配置

小樊
47
2025-10-08 02:40:40
栏目: 编程语言

Installing Golang on Ubuntu
To run Golang programs on Ubuntu, you first need to install the Go environment. Common methods include using the APT package manager (for quick installation) or manually downloading the official binary (for version control).

Configuring Environment Variables
After installation, set up environment variables to enable Go commands in any terminal session. Key variables include GOROOT (Go installation path), GOPATH (workspace directory), and PATH (binary executable paths).

Verify environment setup with go env, which should show correct values for GOROOT, GOPATH, and PATH.

Running a Simple Go Program
Create a basic “Hello, World!” program to test your setup:

  1. Create a project directory and navigate to it:
    mkdir -p ~/go_projects && cd ~/go_projects
    
  2. Initialize a Go module (recommended for dependency management):
    go mod init example.com/hello
    
  3. Write a Go program (hello.go):
    package main
    import "fmt"
    func main() {
        fmt.Println("Hello, World!")
    }
    
  4. Run the program directly using go run:
    go run hello.go
    
    Expected output: Hello, World!\n.

Optional: Configure Go Modules
Go Modules is the standard dependency management tool. Enable it by setting the GO111MODULE environment variable to on (default in newer Go versions):

go env -w GO111MODULE=on

This allows you to manage dependencies efficiently for larger projects.

Installing Development Tools (Optional)
For a better development experience, install tools like golint (code style checker) and delve (debugger):

go install golang.org/x/tools/gopls@latest  # Language server for VS Code
go install github.com/go-delve/delve/cmd/dlv@latest  # Debugger

Verify installations with gopls --version and dlv version.

Deploying a Go Application (Optional)
To deploy a Go application (e.g., a web server built with Fiber), compile it into a binary and run it:

  1. Navigate to your project directory:
    cd ~/go_projects/my-fiber-app
    
  2. Build the application:
    go build -o my-fiber-app
    
  3. Run the binary:
    ./my-fiber-app
    
    The app will start on the specified port (e.g., 3000).

For production, consider using Nginx as a reverse proxy to handle HTTP requests and forward them to your Go application. Install Nginx with sudo apt install nginx, then configure a proxy pass in /etc/nginx/sites-available/default to forward traffic from port 80 to your app’s port (e.g., 3000). Restart Nginx with sudo systemctl restart nginx to apply changes.

0
看了该问题的人还看了