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ā)。
這是一個(gè)基于go應(yīng)用程序命令行的bookstore小項(xiàng)目,具體實(shí)現(xiàn)了圖書(shū)的增刪改查,適合剛?cè)腴T(mén)go的朋友熟悉go的語(yǔ)法。
$ .\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
$ .\bookstore.exe get -id 1
Id Title Author
1 Go語(yǔ)言圣經(jīng) Ailen A
$ .\bookstore.exe add -id 123 -title 'Head First Go' -author unknown
add successfully!
$ .\bookstore.exe add -id 1 -title test -author test
2022/06/24 18:05:44 Book already exists.
$ .\bookstore.exe update -id 123 -title 'head first go' -author UNKNOWN
update successfully!
$ .\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
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)
}
}