讲师中心 微信公众号
AI工具推荐 视频效率加速

How to Correctly Unmarshal YAML in Go

阿萱吖_4514

阿萱吖_4514

发布时间:2026-01-28 11:51:10

|

1038人浏览过

|

来源于php中文网

原创

How to Correctly Unmarshal YAML in Go

this tutorial explains how to properly define go structs for yaml unmarshaling—especially when dealing with nested sequences (like handler lists)—and fixes the common `cannot unmarshal !!seq into map[string][]map[string][]string` error.

YAML is widely used for configuration files due to its readability, but unmarshaling it into Go structs can be tricky—particularly when the structure contains lists (-) of key-value mappings. The root cause of the error cannot unmarshal !!seq into map[string][]map[string][]string is a type mismatch: your YAML defines handlers as a sequence (i.e., a list/array) of mappings (e.g., - url: /.*), but your struct declared Handlers as map[string][]map[string][]string—a deeply nested and incompatible type.

The correct approach is to match Go types to YAML’s logical structure:

  • A YAML list (- item1, - item2) → corresponds to a Go slice: []T
  • Each list item that is a mapping (e.g., url: /.*, secure: always) → corresponds to a map[string]string, provided all keys are strings and values are scalar (strings, numbers, booleans).

Here's the corrected struct:

type AppYAML struct {
    Runtime       string              `yaml:"runtime,omitempty"`
    Handlers      []map[string]string `yaml:"handlers,omitempty"`
    Env_Variables map[string]string   `yaml:"env_variables,omitempty"`
}

✅ Why this works:

Accessory Bundles
Accessory Bundles

为多SKU配件店铺(如全系列手机壳、表带)设计交叉销售和捆绑结构。当用户提及捆绑销售时使用。

下载
  • []map[string]string means “a slice of maps”, matching - url: ..., - static_files: ..., etc.
  • Each handler entry becomes a map[string]string, allowing access like handler["url"] or handler["secure"].

⚠️ Important notes:

  • Use gopkg.in/yaml.v3 instead of v1 (which is deprecated and lacks support for newer YAML features and proper error messages).
  • For better maintainability and type safety, prefer explicit struct fields over map[string]string when the schema is known. Example:
type Handler struct {
    URL         string `yaml:"url,omitempty"`
    Runtime     string `yaml:"runtime,omitempty"`
    Secure      string `yaml:"secure,omitempty"`
    StaticFiles string `yaml:"static_files,omitempty"`
}

type AppYAML struct {
    Runtime       string   `yaml:"runtime,omitempty"`
    Handlers      []Handler `yaml:"handlers,omitempty"`
    Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}

This improves readability, enables compile-time validation, and avoids runtime panics from unexpected keys.

Finally, here’s a complete working example using yaml.v3:

package main

import (
    "fmt"
    "log"
    "gopkg.in/yaml.v3"
)

type Handler struct {
    URL     string `yaml:"url,omitempty"`
    Runtime string `yaml:"runtime,omitempty"`
    Secure  string `yaml:"secure,omitempty"`
}

type AppYAML struct {
    Runtime       string            `yaml:"runtime,omitempty"`
    Handlers      []Handler         `yaml:"handlers,omitempty"`
    Env_Variables map[string]string `yaml:"env_variables,omitempty"`
}

func main() {
    s := `
runtime: go
handlers:
- url: /.*
  runtime: _go_app
  secure: always
env_variables:
  something: 'test'
`

    var a AppYAML
    if err := yaml.Unmarshal([]byte(s), &a); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Runtime: %s\n", a.Runtime)
    for i, h := range a.Handlers {
        fmt.Printf("Handler %d: url=%q, runtime=%q, secure=%q\n", 
            i+1, h.URL, h.Runtime, h.Secure)
    }
    fmt.Printf("Env: %+v\n", a.Env_Variables)
}

? Summary: Always align Go types with YAML’s hierarchical shape—[]T for sequences, map[string]T for mappings—and prefer concrete structs over generic maps when possible. Upgrade to yaml.v3, validate with real examples, and leverage struct tags for precise field control.

热门AI工具

更多
超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

讯飞绘文

讯飞绘文是一款由科大讯飞推出的一站式 AIGC 内容运营平台。

切问学术

切问学术是一款AI论文写作工具,复旦大学NLP团队推出的AI学术智能体。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

墨刀AI
墨刀AI Hot

一款AI图像与设计工具,主要用于产品经理的专属智能体,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

相关专题

更多
golang如何定义变量
golang如何定义变量

golang定义变量的方法:1、声明变量并赋予初始值“var age int =值”;2、声明变量但不赋初始值“var age int”;3、使用短变量声明“age :=值”等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

499

2024.02.23

golang有哪些数据转换方法
golang有哪些数据转换方法

golang数据转换方法:1、类型转换操作符;2、类型断言;3、字符串和数字之间的转换;4、JSON序列化和反序列化;5、使用标准库进行数据转换;6、使用第三方库进行数据转换;7、自定义数据转换函数。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

576

2024.02.23

golang常用库有哪些
golang常用库有哪些

golang常用库有:1、标准库;2、字符串处理库;3、网络库;4、加密库;5、压缩库;6、xml和json解析库;7、日期和时间库;8、数据库操作库;9、文件操作库;10、图像处理库。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

996

2024.02.23

golang和python的区别是什么
golang和python的区别是什么

golang和python的区别是:1、golang是一种编译型语言,而python是一种解释型语言;2、golang天生支持并发编程,而python对并发与并行的支持相对较弱等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

751

2024.03.05

golang是免费的吗
golang是免费的吗

golang是免费的。golang是google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的开源编程语言,采用bsd开源协议。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1466

2024.05.21

golang结构体相关大全
golang结构体相关大全

本专题整合了golang结构体相关大全,想了解更多内容,请阅读专题下面的文章。

4094

2025.06.09

golang相关判断方法
golang相关判断方法

本专题整合了golang相关判断方法,想了解更详细的相关内容,请阅读下面的文章。

1834

2025.06.10

golang数组使用方法
golang数组使用方法

本专题整合了golang数组用法,想了解更多的相关内容,请阅读专题下面的文章。

3786

2025.06.17

PixTV AI视频生成与无限画布创作
PixTV AI视频生成与无限画布创作

PixTV专题整理AI视频与视觉内容创作相关功能使用教程,涵盖AI生图、视频生成、无限画布、多模型创作、素材管理、声音音乐及视频剪辑等功能,帮助用户快速掌握PixTV从创意到成片的完整制作方法。

0

2026.09.29

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn