In the previous chapter, we simply created a module and simply defined a function. Now we continue to complete the module creation.

The code

Before writing, make sure that the greetings module we created earlier already exists. This is the Greetings module we created in the previous chapter.

  1. Create another directoryhelloYou need to keep upgreetingsModules remain at the same level.
     ├── greetings
     └── hello
    Copy the code
  2. Continue to track the current module dependency changes using the module trace command.
    go mod init montos.com/hello
    Copy the code
  3. Carry out ourhello.goCode writing.
    package main
    import (
        "fmt"
        "montos.com/greetings"
    )
    func main(a) {
        // Get a greeting message and print it.
        message := greetings.Hello("Gladys")
        fmt.Println(message)
    }
    Copy the code

    Here’s a quick analysis of what the code does:

    1. First declare the package asmainThe package. (GoThe run code entry must be declared inmainIn the package)
    2. Import two packages:fmtAs well asmontos.com/greetings, followed by a package we created ourselves in the previous section, which is referenced here.
    3. By calling thegreetingsThe function in the package gold is the execution of the local method.
  4. Edit localhelloThe module uses localgreetingsThe module.

    In the case of production use, we are releasing modules to our private repository, and in this demonstration we are directly using local modules.

    1. Run the following command at a command prompt in the Hello directory:
    gomod edit -replace=montos.com/greetings=.. /greetingsCopy the code

    Using this command is to specify that the imported package in the code is replaced by our native package. 2. Run commands to synchronize the current dependencies.

    [root@montos-prod hello]# go mod tidy
    go: found montos.com/greetings in montos.com/greetings v0. 0. 0- 00010101000000.- 000000000000.
    Copy the code
  5. Finally, run the current code environment.
[root@montos-prod hello]# go run .
Hi, Gladys. Welcome!
Copy the code

conclusion

At this point, we have completed a simple dependency module function call. The function is called through local module import dependencies. Simply running a function, the next section will show you how to handle errors in Go and return them in a friendly way.