解决yaml.v2依赖问题

3,757 阅读1分钟

前言

golang 踩坑,其他博客太坑了

问题

  1. 下载 gopkg.in/yaml.v2
go get gopkg.in/yaml.v2
  1. 使用 gopkg.in/yaml.v2 官方提供的例子:
package main

import (
	"fmt"
	"log"

	"gopkg.in/yaml.v2"
)

var data = `
a: Easy!
b:
  c: 2
  d: [3, 4]
`

// Note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type T struct {
	A string
	B struct {
		RenamedC int   `yaml:"c"`
		D        []int `yaml:",flow"`
	}
}

func main() {
	t := T{}

	err := yaml.Unmarshal([]byte(data), &t)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- t:\n%v\n\n", t)

	d, err := yaml.Marshal(&t)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- t dump:\n%s\n\n", string(d))

	m := make(map[interface{}]interface{})

	err = yaml.Unmarshal([]byte(data), &m)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- m:\n%v\n\n", m)

	d, err = yaml.Marshal(&m)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- m dump:\n%s\n\n", string(d))
}

均会出现问题:

go: finding module for package gopkg.in/yaml.v2
main.go:7:2: cannot find module providing package gopkg.in/yaml.v2: unrecognized import path "gopkg.in": parse https://gopkg.in/?go-get=1: no go-import meta tags ()

解决方法

查看官方文档:labix.org/gopkg.in 其中提到:

The actual implementation of the package is in GitHub:

https://github.com/go-yaml/yaml

因此,改用

go get github.com/go-yaml/yaml

将官方例子的 import 改为:

import (
	"fmt"
	"log"

	"github.com/go-yaml/yaml"
)

执行成功:

--- t:
{Easy! {2 [3 4]}}

--- t dump:
a: Easy!
b:
  c: 2
  d: [3, 4]


--- m:
map[a:Easy! b:map[c:2 d:[3 4]]]

--- m dump:
a: Easy!
b:
  c: 2
  d:
  - 3
  - 4