当前位置:网站首页>Intelligent online customer service system source code Gofly development log - 2 Develop command line applications

Intelligent online customer service system source code Gofly development log - 2 Develop command line applications

2022-07-06 21:51:00 Taoshihan

I've always done PHP Development , Unless it's using swoole frame , Most of the PHP Applications send code to the corresponding directory of the server , start-up nginx+php-fpm To run the PHP Code .

golang and PHP It's different ,golang It can be run as a back-end service listening port , At this time, you should be able to start and pass parameters on the command line .

choose github.com/spf13/cobra This library handles the parsing of command line parameters . You can distinguish the different actions you want to perform through the command line , Different parameters must be passed in different actions

For example, the function I implemented is ./go-fly-pro server Enable the listening port service ,./go-fly-pro install Is the script to import the database , This is the second parameter of the command line to distinguish different actions

The third to last parameter of the command is to pass different configuration parameters , I realized ./go-fly-pro server -p Port number   , You can configure to listen to different ports , This is the main logic of the command line application .

The entry file is go-fly.go , It is called directly cmd Bag Execute Method

package main

import (
    "go-fly-muti/cmd"
)

func main() {
    cmd.Execute()
}

Self defined cmd Package is the function package of command line application , There is an entrance method , There are global variables , There are initialization actions

Every action is a cobra.Command Structural entities


package cmd

import (
    "github.com/spf13/cobra"
    "log"
    "os"
)

var rootCmd = &cobra.Command{
    Use:   "go-fly-pro",
    Short: "go-fly-pro",
    Long:  ` Simple and fast GO Language online customer service system GOFLY`,
}

func init() {
    rootCmd.AddCommand(serverCmd)
    rootCmd.AddCommand(installCmd)
    rootCmd.AddCommand(stopCmd)
    rootCmd.AddCommand(indexCmd)
}
func Execute() {
    if err := rootCmd.Execute(); err != nil {
        log.Println(" Execute command parameter error :", err)
        os.Exit(1)
    }
}

This is the command line entry file , What problems and knowledge points will be summarized later .

原网站

版权声明
本文为[Taoshihan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131110570330.html