go language go mod generated

1. go hello world

Create a folder gotest, create a test1.go file in it, and write

package main

import (

	"fmt"
)

func main() {
	fmt.Println("hello world")
}

 run command

go run test1.go

You can see the output hello world

2. Using the cli command line

code show as below:

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/urfave/cli/v2"
)

func main() {

	app := &cli.App{
		Name:  "hello",
		Usage: "hello world example",
		Action: func(c *cli.Context) error {
			fmt.Println("hello world")
			return nil
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
	// fmt.Println("hello world")
}

Run: go build -o test1

It may run wrong and the package cannot be found. At this point, the package can be managed by generating the go.mod file

 Generate go.mod file 

go mod init gotest //where gotest is the name of the folder where the go file is located 

Notice:

In the above, after we generated the go.mod file through the go mod init xxx command, this is just an empty file, and the various packages that depend on it have not been generated yet.

You can use the following two commands to obtain:

<1> go get package name example: go get github.com/urfave/cli/v2

If there are many dependent packages, then go get is more troublesome. Another command can be used:

<2> go mod tidy This command will scan all the imported library packages in the .go file we wrote, and generate corresponding records into the go.mod file.

2.1 cli.Context

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/urfave/cli/v2"
)

func main() {

	app := &cli.App{
		Name:  "hello",
		Usage: "hello world example",
		Action: func(c *cli.Context) error {
			// fmt.Println("hello world")
			fmt.Printf("Hello %s", c.Args().Get(0))
			return nil
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
	// fmt.Println("hello world")
}

operation result:

c.Args() //You can get the parameter list after running the command, which is a slice, cCtx.Args().Get(0) is to get the parameter of the first position, the second and third and so on

fmt package output function

func Print(a ...interface{}) (n int, err error)

func Printf(format string, a ...interface{}) (n int err error)

func Printfln(a ...interface{}) (n int, err error)

 reference:

https://juejin.cn/post/7098296317394288671

Guess you like

Origin blog.csdn.net/guaizaiguaizai/article/details/132489762