首页主机资讯Golang在CentOS上的Web开发实践

Golang在CentOS上的Web开发实践

时间2025-11-13 20:56:03发布访客分类主机资讯浏览696
导读:Installing Golang on CentOS To start Web development with Golang on CentOS, first install the Go environment. You can us...

Installing Golang on CentOS
To start Web development with Golang on CentOS, first install the Go environment. You can use either yum (simpler) or manual installation (more control). For manual installation:

  1. Download the latest stable Go package (e.g., go1.21.0.linux-amd64.tar.gz) from the official website.
  2. Extract it to /usr/local:
    sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
    
  3. Configure environment variables by adding these lines to /etc/profile.d/golang.sh:
    export GOROOT=/usr/local/go
    export GOPATH=$HOME/go
    export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
    
  4. Reload the profile:
    source /etc/profile.d/golang.sh
    
  5. Verify installation with go version, which should display the installed Go version.

Creating a Simple Web Application
With Go installed, create a basic Web server using the standard net/http package (for simplicity) or a framework like Gin. Here’s an example using net/http:

  1. Create a project directory and initialize a module:
    mkdir mywebserver &
        &
     cd mywebserver
    go mod init example.com/mywebserver
    
  2. Write a simple handler in 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("Server running on :8080")
        if err := http.ListenAndServe(":8080", nil);
     err != nil {
    
            fmt.Println("Error starting server:", err)
        }
    
    }
    
    
  3. Run the application:
    go run main.go
    
  4. Access it in a browser at http://your_server_ip:8080 to see “Hello, World!”.

Using a Web Framework (Gin Example)
For more structured and scalable Web development, use a framework like Gin (a high-performance HTTP router). Here’s how to set it up:

  1. Install Gin using Go modules:
    go get -u github.com/gin-gonic/gin
    
  2. Create a main.go file with Gin:
    package main
    
    import "github.com/gin-gonic/gin"
    
    func main() {
    
        r := gin.Default()
        r.GET("/", func(c *gin.Context) {
    
            c.JSON(200, gin.H{
    "message": "Hello, World!"}
    )
        }
    )
        r.Run() // Defaults to :8080
    }
    
    
  3. Run the application:
    go run main.go
    
  4. Access http://your_server_ip:8080 to see a JSON response: { "message":"Hello, World!"} .

Deploying to Production
For production, you need to manage processes, configure firewalls, and use a reverse proxy. Here’s a step-by-step guide:

  1. Configure Firewall: Allow HTTP (port 80) and HTTPS (port 443) traffic using firewalld:
    sudo systemctl start firewalld
    sudo firewall-cmd --permanent --zone=public --add-service=http
    sudo firewall-cmd --permanent --zone=public --add-service=https
    sudo firewall-cmd --reload
    
  2. Use Systemd for Process Management: Create a systemd service file (/etc/systemd/system/mywebserver.service) to manage your Go app:
    [Unit]
    Description=My Go Web Server
    After=network.target
    
    [Service]
    User=your_username
    Group=your_groupname
    ExecStart=/usr/bin/go run /path/to/your/webserver/main.go
    Restart=always
    Environment=GOPATH=/home/your_username/go
    
    [Install]
    WantedBy=multi-user.target
    
    Reload systemd, start the service, and enable it to run on boot:
    sudo systemctl daemon-reload
    sudo systemctl start mywebserver
    sudo systemctl enable mywebserver
    
  3. Set Up Nginx as a Reverse Proxy: Install Nginx and configure it to forward requests to your Go app. Create a new Nginx config file (/etc/nginx/conf.d/mywebserver.conf):
    server {
        
        listen 80;
        
        server_name your_domain_or_ip;
    
    
        location / {
        
            proxy_pass http://localhost:8080;
         # Forward to your Go app
            proxy_set_header Host $host;
        
            proxy_set_header X-Real-IP $remote_addr;
        
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
        }
    
    }
        
    
    Test the Nginx configuration, reload it, and restart the service:
    sudo nginx -t
    sudo systemctl reload nginx
    sudo systemctl restart nginx
    
    Now, your Go app is accessible via http://your_domain_or_ip, with Nginx handling SSL termination, load balancing, and static files.

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Golang在CentOS上的Web开发实践
本文地址: https://pptw.com/jishu/747441.html
centos上laravel模板怎么使用 CentOS如何配置Golang的HTTP服务器

游客 回复需填写必要信息