go模块N

218 阅读3分钟

创建模块

创建目录:mkdir greetings
进入目录:cd greetings
创建mod依赖:go mod init example/greetings
创建文件:greetings.go 
编辑文件:#模块名与文件名,目录名均相同

package greetings    
import "fmt"    
func Hello(name string) string {       
    message := fmt.Sprintf("Hi, %v. Welcome!", name)        
    return message  
 }

创建主程序

返回greetings目录上层,创建目录:

    cd ..        
    mkdir hello
    cd hello

创建mod依赖:

   go mod init example/hello

创建文件hello.go:

package main   
    import (        "fmt"      
    "example.com/greetings"   
)   
func main() {    
    // Get a greeting message and print it.     
    message := greetings.Hello("Gladys")       
    fmt.Println(message)   
}

改变模块查找方式:改为相对地址

go mod edit -replace example.com/greetings=../greetings

更新依赖:

go mod tidy

运行代码:

go run .

返回错误

修改greetings.go

package greetings
import (    
    "errors"  
    "fmt"
 )  
 func Hello(name string)(string, error){  
     if name == "" {      
         return "", errors.New("empty name")   
     }
     message := fmt.Sprintf("Hi, %v. Welcome!", name)   
     return message, nil
 }

修改hello.go

package main
import ( 
    "fmt"
    "log""example.com/greetings"
 )
 func main() {   
     log.SetPrefix("greetings: ")   
     log.SetFlags(0)message, err := greetings.Hello("")   
     if err != nil {      
         log.Fatal(err)   
      }
     fmt.Println(message)}

运行代码:

go run .

返回随机的结果

修改greetings/greetings.go

package greetings

import (
    "errors"
    "fmt"
    "math/rand"
    "time"
)

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return name, errors.New("empty name")
    }
    // Create a message using a random format.
    message := fmt.Sprintf(randomFormat(), name)
    return message, nil
}

// init sets initial values for variables used in the function.
func init() {
    rand.Seed(time.Now().UnixNano())
}

// randomFormat returns one of a set of greeting messages. The returned
// message is selected at random.
func randomFormat() string {
    // A slice of message formats.
    formats := []string{
        "Hi, %v. Welcome!",
        "Great to see you, %v!",
        "Hail, %v! Well met!",
    }

    // Return a randomly selected message format by specifying
    // a random index for the slice of formats.
    return formats[rand.Intn(len(formats))]
}

修改hello/hello.go

package main

import (
    "fmt"
    "log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // Request a greeting message.
    message, err := greetings.Hello("Gladys")
    // If an error was returned, print it to the console and
    // exit the program.
    if err != nil {
        log.Fatal(err)
    }

    // If no error was returned, print the returned message
    // to the console.
    fmt.Println(message)
}

运行

go run .

返回多值结果

修改greetings/greetings.go

package greetings

import (
    "errors"
    "fmt"
    "math/rand"
    "time"
)

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return name, errors.New("empty name")
    }
    // Create a message using a random format.
    message := fmt.Sprintf(randomFormat(), name)
    return message, nil
}

// Hellos returns a map that associates each of the named people
// with a greeting message.
func Hellos(names []string) (map[string]string, error) {
    // A map to associate names with messages.
    messages := make(map[string]string)
    // Loop through the received slice of names, calling
    // the Hello function to get a message for each name.
    for _, name := range names {
        message, err := Hello(name)
        if err != nil {
            return nil, err
        }
        // In the map, associate the retrieved message with
        // the name.
        messages[name] = message
    }
    return messages, nil
}

// Init sets initial values for variables used in the function.
func init() {
    rand.Seed(time.Now().UnixNano())
}

// randomFormat returns one of a set of greeting messages. The returned
// message is selected at random.
func randomFormat() string {
    // A slice of message formats.
    formats := []string{
        "Hi, %v. Welcome!",
        "Great to see you, %v!",
        "Hail, %v! Well met!",
    }

    // Return one of the message formats selected at random.
    return formats[rand.Intn(len(formats))]
}

修改hello/hello.go

package main

import (
    "fmt"
    "log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // A slice of names.
    names := []string{"Gladys", "Samantha", "Darrin"}

    // Request greeting messages for the names.
    messages, err := greetings.Hellos(names)
    if err != nil {
        log.Fatal(err)
    }
    // If no error was returned, print the returned map of
    // messages to the console.
    fmt.Println(messages)
}

添加测试文件

创建目录:以_test.go结尾告诉程序此处为测试; greetings\greetings_test.go.

package greetings

import (
    "testing"
    "regexp"
)

// TestHelloName calls greetings.Hello with a name, checking
// for a valid return value.
func TestHelloName(t *testing.T) {
    name := "Gladys"
    want := regexp.MustCompile(`\b`+name+`\b`)
    msg, err := Hello("Gladys")
    if !want.MatchString(msg) || err != nil {
        t.Fatalf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)
    }
}

// TestHelloEmpty calls greetings.Hello with an empty string,
// checking for an error.
func TestHelloEmpty(t *testing.T) {
    msg, err := Hello("")
    if msg != "" || err == nil {
        t.Fatalf(`Hello("") = %q, %v, want "", error`, msg, err)
    }
}

运行test

go test  |  go test -v

中断功能以查看失败的测试

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return name, errors.New("empty name")
    }
    // Create a message using a random format.
    // message := fmt.Sprintf(randomFormat(), name)
    message := fmt.Sprint(randomFormat())
    return message, nil
}

编译和安装应用程序

命令:

go build #编译包及其依赖关系,不安装结果
go install #编译和安装包

编译

go build #产生hello.exe

查找安装路径

go list -f '{{.Target}}'

添加到路径

export PATH=$PATH:/path/to/your/install/directory
set PATH=%PATH%;C:\path\to\your\install\directory

或设置 go bin

 go env -w GOBIN=/path/to/your/bin
go env -w GOBIN=C:\path\to\your\bin

编译安装

go install

运行

 hello