【Go語言學習】Agenda-cli程序簡要說明(只包含對用戶操作的指令實現)

寫在前面

  • 實驗資料在老師的課程網站上發佈:傳送門
  • 由於完全實現Agenda需要大量時間,所以本次實驗是簡化版,主要目的是爲了熟悉GO語言的io操作和cobra庫的使用,實現一個簡單的命令行程序。
  • 本次實驗項目放到Go-online在線IDE上,分享鏈接: 傳送門

Agenda程序簡介

使用簡單的命令行程序,能夠讓用戶執行登錄、註冊等賬戶操作,並且能夠創建會議,選擇參加或退出會議等操作。
完整版的Agenda就是一個會議管理系統,但是這次作業,降低了難度,使用了簡化版的實現,也就是隻實現了部分功能。

使用Corba實現

  • 使用命令 go get -v github.com/spf13/cobra/cobra 下載過程中,會出提示如下錯誤

    Fetching https://golang.org/x/sys/unix?go-get=1
    https fetch failed: Get https://golang.org/x/sys/unix?go-get=1: dial tcp 216.239.37.1:443: i/o timeout
    

這是熟悉的錯誤,請在 $GOPATH/src/golang.org/x 目錄下用 git clone 下載 systext 項目,然後使用 go install github.com/spf13/cobra/cobra, 安裝後在 $GOBIN 下出現了 cobra 可執行程序。

Cobra的使用十分簡單,直接使用cobra init --pkg-name 創建項目,然後就會有一個你剛剛命名的項目目錄,裏面有cmd的子目錄、main.go文件、LICENSE文件,其中cmd文件下放着各種子命令的實現文件,main就是整個程序的運行文件,比如這次agenda,輸入指令就需要先運行agenda,再加上子命令以及參數來運行。
在這裏插入圖片描述
由以上目錄可以看到,本次實現了登錄、註冊、註銷、刪除賬號、查看賬戶信息的功能。

entity的目錄主要是存放用戶操作的邏輯以及數據交互的程序文件,每次執行一個子命令,就會調用entity中的函數,進行邏輯判斷如操作是否正確,有無衝突。還需要對交互的信息進行數據存儲,如註冊用戶後,將用戶信息存放到json文件中去等

以註冊操作爲例,簡要說明實現

package cmd
/*
Copyright © 2019 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


import (
	"fmt"

    "git.go-online.org.cn/hsyjkjkl/agenda/entity"
	"github.com/spf13/cobra"
)

// registerCmd represents the register command
var registerCmd = &cobra.Command{
	Use:   "register",
	Short: "regist a new user",
	Long: `register command will help you regist!
	It need you to name a new user and also you should give your email
	your phone number and your password
	the name should not be used before`,

	Run: func(cmd *cobra.Command, args []string) {
		username, _ := cmd.Flags().GetString("username")
		password, _ := cmd.Flags().GetString("password")
		email, _ := cmd.Flags().GetString("email")
		phone, _ := cmd.Flags().GetString("phone")

		s1, s2 := entity.UserRegist(username, password, email, phone)
		if s1 {
			fmt.Printf("Regist new user : \"%v\" successfully!\n", username)
		}
		if s2 {
			fmt.Println("Auto Login...")
		}
	},
}

func init() {
	rootCmd.AddCommand(registerCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// registerCmd.PersistentFlags().String("foo", "", "A help for foo")

	registerCmd.Flags().StringP("username", "u", "", "username not be used")
	registerCmd.Flags().StringP("password", "p", "", "password to login")
	registerCmd.Flags().StringP("email", "e", "", "your email address")
	registerCmd.Flags().StringP("phone", "", "", "your cell phone number")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// registerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

首先可以在當前目錄下使用cobra add register 來創建register這個子命令得文件,這時候,就會自動創建一個模板文件,init中定義參數(類似pflags),然後在registerCmd這個結構體中定義相應的信息,如長描述、短描述,更重要的是Run中運行的邏輯,這裏我直接調用了entity中的註冊函數:

//UserRegist : regist user
func UserRegist(username, password, email, phone string) (bool, bool) {
	state := false
	if username == "" || password == "" || email == "" || phone == "" {
		fmt.Printf("[Regist Failed]: Please ensure you enter all information of register, -u username -p password -e email --phone phoneNumber\n")
		return false, false
	}

	var tmpList []UserInfo
	tmpList = GetAllUsers()

	if UserExisted(username, tmpList) {
		fmt.Printf("[Regist failed]: Username already exited! Please try another one.\n")
		return false, false
	}

	tmp := NewUser(username, password, email, phone)
	tmpList = append(tmpList, tmp)
	SaveAllUser(tmpList)

	if GetCurrentUser() == "" {
		UserLogin(tmp.Username, tmp.Password)
		state = true
	}

	return true, state
}

首先判斷是否有完整個人信息,包括用戶名、密碼、郵箱、電話,其次檢測是否存在已註冊的同名用戶,否則將信息加入到json文件中去,如果當前沒有用戶在登錄,就直接自動登錄。返回狀態信息。

其他的命令也可以類似的實現,這裏涉及到Agenda的邏輯判斷問題,之前實訓的時候已經做過一次,就不再重複講了,有興趣可以參照代碼理解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章