真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

go入門(mén)項(xiàng)目:(1) 基于命令行的圖書(shū)的增刪查改

Go 語(yǔ)言入門(mén)練手項(xiàng)目系列

創(chuàng)新互聯(lián)長(zhǎng)期為千余家客戶(hù)提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為江漢企業(yè)提供專(zhuān)業(yè)的成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站,江漢網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

  • 01 基于命令行的圖書(shū)的增刪查改
  • 02 文件管理
    持續(xù)更新中...

> 本文來(lái)創(chuàng)新互聯(lián)建設(shè)站,作者:小程,轉(zhuǎn)載請(qǐng)注明原文鏈接:https://www.cdcxhl.com/article39/dsoicph.html

介紹

這是一個(gè)基于go應(yīng)用程序命令行的bookstore小項(xiàng)目,具體實(shí)現(xiàn)了圖書(shū)的增刪改查,適合剛?cè)腴T(mén)go的朋友熟悉go的語(yǔ)法。

知識(shí)點(diǎn)

  • go flag,提供了命令行參數(shù)解析的功能
  • go json的序列化與反序列化
  • go ioutil 讀寫(xiě)文件

功能演示

  1. 列出全部圖書(shū)
$ .\bookstore.exe get -all
Id      Title                   Author
1       Go語(yǔ)言圣經(jīng)              Ailen A
2       Java編程思想            Bruce Eckel
3       流暢的Python            Luciano Ramalho
4       PHP權(quán)威指南             CENJW 
  1. 通過(guò)id獲取相應(yīng)圖書(shū)
$ .\bookstore.exe get -id 1
Id      Title           Author
1       Go語(yǔ)言圣經(jīng)      Ailen A 
  1. 添加圖書(shū)
$ .\bookstore.exe add -id 123 -title 'Head First Go' -author unknown
add successfully! 
  1. 添加圖書(shū),如果已經(jīng)存在相同id的圖書(shū),提示已存在
$ .\bookstore.exe add -id 1 -title test -author test 
2022/06/24 18:05:44 Book already exists. 
  1. 更新圖書(shū)
$ .\bookstore.exe update -id 123 -title 'head first go' -author UNKNOWN
update successfully! 
  1. 刪除圖書(shū)
$ .\bookstore.exe delete -id 123
Delete successfully! 

本文來(lái)自創(chuàng)新互聯(lián)建設(shè)站,作者:小譚,轉(zhuǎn)載請(qǐng)注明原文鏈接:https://www.cdcxhl.com/article39/dsoicph.html

功能實(shí)現(xiàn)

main.go

func main() {
	// get book/books
	getCmd := flag.NewFlagSet("get", flag.ExitOnError)
	getAll := getCmd.Bool("all", false, "List all books")
	getId := getCmd.String("id", "", "Get a book by id")

	// add/update book
	addCmd := flag.NewFlagSet("add", flag.ExitOnError)
	addId := addCmd.String("id", "", "Book id")
	addTitle := addCmd.String("title", "", "Book title")
	addAuthor := addCmd.String("author", "", "Book author")

	// delete book
	deleteCmd := flag.NewFlagSet("delete", flag.ExitOnError)
	deleteId := deleteCmd.String("id", "", "Book id")
	
	// check command
	if len(os.Args) < 2 { log.Fatal("Expected get, add, update, delete commands.") } switch os.Args[1] { case "get": handleGetBooks(getCmd, getAll, getId) case "add": handleAddOrUpdateBook(addCmd, addId, addTitle, addAuthor, true) case "update": handleAddOrUpdateBook(addCmd, addId, addTitle, addAuthor, false) case "delete": handleDeleteBook(deleteCmd, deleteId) default: fmt.Println("Pls provide get, add, update, delete commands.") } } 

books.go

type Book struct {
	Id     string `json:"id"`
	Title  string `json:"title"`
	Author string `json:"author"`
}

// get all the books logic
func handleGetBooks(getCmd *flag.FlagSet, all *bool, id *string) {
	getCmd.Parse(os.Args[2:])

	if !*all && *id == "" {
		fmt.Println("subcommand --all or --id needed") // PrintDefault打印集合中所有注冊(cè)好的flag的默認(rèn)值。除非另外配置,默認(rèn)輸出到標(biāo)準(zhǔn)錯(cuò)誤輸出中。
		getCmd.PrintDefaults()
		os.Exit(1)
	}

	if *all {
		books := getBooks()
		fmt.Println("Id\tTitle\t\t\tAuthor\t")
		for _, book := range books {
			fmt.Printf("%v\t%v\t\t%v\t\n", book.Id, book.Title, book.Author)
		}
	}

	if *id != "" {
		var isExist bool
		books := getBooks()
		fmt.Println("Id\tTitle\t\tAuthor\t")
		for _, book := range books {
			if book.Id == *id {
				fmt.Printf("%v\t%v\t%v\t\n", book.Id, book.Title, book.Author)
				isExist = true
			}
		}

		if !isExist {
			log.Fatal("Book not found!")
		}
	}
}

// add or update a book logic
// addBook: true denote add a new book to file, false denote update a book
func handleAddOrUpdateBook(addCmd *flag.FlagSet, id, title, author *string, addBook bool) {
	addCmd.Parse(os.Args[2:])

	if *id == "" || *title == "" || *author == "" {
		addCmd.PrintDefaults()
		log.Fatal("Pls provide id, title, author commands.")
	}
	books := getBooks()
	var newBook Book
	if addBook {
		for _, book := range books {
			if book.Id == *id {
				log.Fatal("Book already exists.")	
			} else {
				newBook = Book{*id, *title, *author}
				books = append(books, newBook)
				break
			}
		}
		
	} else {
		var isExist bool
		for i, book := range books {
			if book.Id == *id {
				books[i] = Book{Id: *id, Title: *title, Author: *author}
				isExist = true
			}
		}

		err := saveBooks(books)
		checkError(err)

		if !isExist {
			log.Fatal("Book not found")
		}

	}

	saveBooks(books)

	fmt.Printf("%s successfully!\n", os.Args[1])
}

func handleDeleteBook(deleteCmd *flag.FlagSet, id *string) {
	deleteCmd.Parse(os.Args[2:])

	if *id == "" {
		deleteCmd.PrintDefaults()
		log.Fatal("Pls provide id command.")
	}

	if *id != "" {
		var isExist bool
		books := getBooks()
		for i, book := range books {
			if book.Id == *id {
				books = append(books[:i], books[i+1:]...)
				isExist = true
			}
		}

		if !isExist {
			log.Fatal("Book not found!")
		}

		err := saveBooks(books)
		checkError(err)

		fmt.Println("Delete successfully!")
	}
}

func saveBooks(books []Book) error {
	bookBytes, err := json.Marshal(books)
	checkError(err)
	err = ioutil.WriteFile("./books.json", bookBytes, 0644)
	return err
}

func getBooks() (books []Book) {
	bookBytes, err := ioutil.ReadFile("./books.json")
	checkError(err)
	err = json.Unmarshal(bookBytes, &books)
	checkError(err)
	return books
}

func checkError(err error) {
	if err != nil {
		log.Fatal("Error happended ", err)
	}
} 

本文題目:go入門(mén)項(xiàng)目:(1) 基于命令行的圖書(shū)的增刪查改
網(wǎng)頁(yè)URL:http://weahome.cn/article/dsoicph.html

其他資訊

在線咨詢(xún)

微信咨詢(xún)

電話(huà)咨詢(xún)

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部