| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 
 | 1.体脂计算器接受从命令行传入的姓名、性别、身高、体重、年龄、直接计算出其体脂并给出结果。
 2.引入命令行使用工具包方式
 - _ "github.com/spf13/cobra"
 - go mod tidy
 - 按住command键盘,鼠标点一下cobra,会自动跳转到包目录位置。
 3. go mod init 说明:
 - 如果在GOPATH下 可以直接指向go mod init
 - 如果项目不在GOPATH下,需要指定路径: go mod init example/module,执行代码 需要go run ./main.go 指定下,否则可能会报错。
 4.Go Module替换
 - Go Module 替换(replace)是用另一个实现替换默认要使用的实现。类似"狸猫换太子"。
 
 module lesson2/13.read
 
 go 1.17
 
 require (
 github.com/spf13/cobra v1.3.0
 learn.go.tools v0.0.0-00010101000000-000000000000
 )
 
 require (
 github.com/inconshreveable/mousetrap v1.0.0
 github.com/spf13/pflag v1.0.5
 )
 
 
 replace learn.go.tools => ../../learn.go.tools
 
 - 编辑完毕后执行 go mod tidy即可
 - [jwgod@infra 13.read %]# go mod tidy
 - go: found learn.go.tools in learn.go.tools v0.0.0-00010101000000-000000000000
 
 5.项目核心代码
 
 package main
 
 import (
 "fmt"
 "github.com/spf13/cobra"
 "lesson2/13.read/sex"
 "lesson2/13.read/bmi"
 "lesson2/13.read/bfr"
 "learn.go.tools"
 )
 
 var (
 Name   string
 Sex    string
 Tall   float64
 Weight float64
 Age    float64
 )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 func InputFromCobra(){
 cmd := cobra.Command{
 Use: "healthcheck",
 Short: "体脂计算器,根据身高,体重,性别,年龄计算体制比,给出建议。",
 Long: "该体脂计算器是基于bmi的体脂计算器进行计算的...",
 Run: func(cmd *cobra.Command, args []string) {
 fmt.Println("Name:", Name)
 fmt.Println("Sex:", Sex)
 fmt.Println("Tall:", Tall)
 fmt.Println("Weight:", Weight)
 fmt.Println("Age:", Age)
 
 
 bmiResult := bmi.GetBMI(Tall,Weight)
 bfrResult := bfr.GetBFR(bmiResult,Age,sex.GetSexWeight(Sex))
 fmt.Printf("bmi:%v,bfr:%v\n",bmiResult,bfrResult)
 fmt.Println(learn_go_tools.Max(3,100))
 
 },
 }
 
 cmd.Flags().StringVar(&Name,"Name","","姓名")
 cmd.Flags().StringVar(&Sex,"Sex","","姓别")
 cmd.Flags().Float64Var(&Tall,"Tall",-1,"身高")
 cmd.Flags().Float64Var(&Weight,"Weight",-1,"体重")
 cmd.Flags().Float64Var(&Age,"Age",-1,"年龄")
 
 
 cmd.Execute()
 }
 
 func main() {
 
 InputFromCobra()
 }
 
 6.go.mod replace
 - go.mod 文件中 包版本可以写 master or v1.2.1 这两种类型。
 - replace learn.go.tools => ../../learn.go.tools master
 
 |