Go-gin implements api to change file configuration

There are two test environments dev and test. Due to the restrictions set by the official account, only two callback domain names can be set. The production environment occupies one, and the test can only switch back and forth. The test and the front end always ask which environment they are in. Write a script, be rude, to receive parameters, read files and regularize, and execute linux commands. (No error handling is not advisable)

Route 1: http://xx.com:8090/wechatGet the current environment
Route 2: http://xx.com:8090/wechat?env=XXModify the interface proxy environment of the nginx configuration file and reload the
program background hangs:nohup go run ./wechat_env.go &

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"regexp"
	"github.com/gin-gonic/gin"
)

var r = gin.New()

func main() {
    
    
	gin.ForceConsoleColor()
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	r.GET("/wechat", func(c *gin.Context) {
    
    
		env := c.DefaultQuery("env", "")
		filePath := "/etc/nginx/sites-enabled/new_wechat.conf"
		msg := ""
		switch env {
    
    
		case "":
			env = GetEnv(filePath)
			msg = "当前环境为" + env
		case "dev":
			fallthrough
		case "test":
			// 修改配置
			conf := ModifyConfig(env)
			// 加载配置
			NginxReload(conf, filePath)
			msg = "环境切换" + env + "成功"
			break
		default:
			msg = "环境参数错误"
		}

		c.JSON(http.StatusOK, gin.H{
    
    
			"message": msg,
		})
		return
	})

	r.Run(":8090")
}

# 获取当前环境,使用正则匹配
func GetEnv(filePath string) string {
    
    
	conf, _ := ioutil.ReadFile(filePath)
	reg := regexp.MustCompile(`http://local\.yxt-up-api-([a-z]+)`)
	result := reg.FindAllStringSubmatch(string(conf), -1)
	log.Println("当前环境:" + result[0][1])
	return result[0][1]
}

# 修改配置文件,其实只是模板的sprintf
func ModifyConfig(env string) string {
    
    
	template := `
# %s
server {
	listen 80;
	server_name _;
	root /vda2/var/www/new-wechat/dist;

	location / {
		try_files \$uri \$uri/ /index.html;
	}

	location /api/ {
		proxy_pass http://local.yxt-up-api-%s/;
	}

}
	`
	log.Println("修改环境为:" + env)
	return fmt.Sprintf(template, env, env)
}

# 修改文件,并重加载nginx配置
func NginxReload(conf string, filePath string) {
    
    
	cmd1 := `echo "` + conf + `" > ` + filePath
	exec.Command("bash", "-c", cmd1).Run()
	err := exec.Command("bash", "-c", "nginx -s reload").Run()
	if err != nil {
    
    
		log.Println(err)
	}
}

Guess you like

Origin blog.csdn.net/z772532526/article/details/112479240