Go语言学习之Struct中的Tag

简介

Tag可选的字段:

  • "-" :不要解析这个字段
  • "omitempty":当字段为空(默认值)时,不要解析这个字段;比如是false、0、nil或者长度为0的array、map、slice、string等
  • FieldName:当解析json、xml、ini等的时候 用这个名字

YAML配置文件和Struct Tag的结合使用

一、新建YAML配置文件

######config.yaml########

http:
  port: 8090
  domain: baidu
  secretKey: test

二、在程序中使用配置文件获取参数‘

package config

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "io/ioutil"
)

//Config和Http 为嵌套关系
type Config struct {
    Http         `yaml:"http"`
}

type Http struct {
    Port    string    `yaml:"port"`
    Secret  string    `yaml:"secretKey"`
    Domain    string  `yaml:"domain"`
}


func  Init() *Config {
  //初始化Config 结构体 Conf :
= new(Config)
//读取配置文件 yamlFile, err :
= ioutil.ReadFile("config.yaml") if err != nil { fmt.Println(err.Error()) }
  //把YAML配置文件和Config结构体绑定,一对一映射,因为结构体的别名(yaml:port,yaml:secretKey,yaml:domain和YAML配置文件里的Key是一样的,所以能一对一映射上,把YAML配置文件的值赋值给结构体) err
= yaml.Unmarshal(yamlFile, Conf)
  //通过打印Config这个结构的Key能获取通过YAML配置文件映射的值 fmt.Println(Conf.Domain,Conf.Port,Conf.Secret)
if err != nil { fmt.Println(err.Error()) } return Conf
##########结果
baidu 8090 test

JSON和Struct Tag结合使用

不加Json Tag

package main

import (
    "encoding/json"
    "fmt"
)

type peerInfo struct {
    HTTPPort int
    TCPPort  int
    versiong string
}

func main() {
  //实例化结构体 pi :
= peerInfo{80, 3306, "0.0.1"}
  // 把p1结构体给转换成json js, err :
= json.Marshal(pi) if err != nil { fmt.Println(err) }
  //打印转换成json之后的结构体 fmt.Println(
string(js)) }

输出结果

{"http_port":80,"tcp_port":3306}

加Json Tag

type NetConf struct {
    Master string `json:"master"`
    Mode   string `json:"mode"`
    MTU    int    `json:"mtu"`
    Debug  bool   `json:"debug"`
}

func main() {
    //实例化结构体,就是给结构体赋值
    n := NetConf{"master1", "mode1", 1500, true}
    //把结构体转换成json
    if d,e:=json.Marshal(n);e==nil{
        fmt.Println(string(d))
    }
}

输出结果

{"master":"master1","mode":"mode1","mtu":1500,"debug":true}

Json配置文件和Struct Tag结合

一、新建json配置文件

config.json

{
  "enabled": true,
  "path": "/usr/local"
}

程序读取JSON配置文件并和struct绑定

type configuration struct {
    Enabled bool    `json:"enabled"`  //必须跟配置文件里的Key一样,否则无法映射
    Path    string    `json:"path"`
}

func main() {
        //读取配置文件
        file, _ := os.Open("config.json")
    defer file.Close()
        //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据
    decoder := json.NewDecoder(file)
        //实例化结构体
    conf1 := configuration{}
        //Decode从输入流读取下一个json编码值并保存在结构体里
    if erre := decoder.Decode(&conf1); erre != nil {
        fmt.Println(erre)
    }

       //打印结构体的属性,json已经把从配置文件读取出来的值绑定到结构体对应的值上了
    fmt.Println(conf1.Enabled)
    fmt.Println(conf1.Path)
} 

Echo框架Post参数结合结构体Tag使用

echo框架读取Post的参数,并把值绑定到结构体

main.go

package main
import (

    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"


)



func main(){
    

    e := echo.New()
    e.Use(middleware.Logger())  //开启Log日志
    e.Use(middleware.Recover())  //Recover 中间件从 panic 链中的任意位置恢复程序, 打印堆栈的错误信息,并将错误集中交给 HTTPErrorHandler 处理
    e.Use(middleware.RequestID()) //为请求生成唯一的 ID
    e.POST("/login",auth.Login)
    e.Start(":8080")


}

login.go

package auth

import (
    "github.com/labstack/echo"
    "net/http"

)

type User struct {
    Name  string `json:"name" form:"name" query:"name"`   //这里的tag表示,json不用说了, 然后form是可以跟POst请求中form表单里的name字段可以绑定,query可以跟query参数绑定,就是get请求
    Password string `json:"password" form:"password" query:"password"`
}

func Login(c echo.Context) (err error){
//为User 结构体分配内存 u :
= new(User)
//把从Post请求读取过来的值绑定到结构体里
if err = c.Bind(u); err != nil { cuowu := "cuowu" return c.String(http.StatusBadGateway,cuowu) }
fmt.Println(u.Name,u.Password)
return c.String(http.StatusOK,u.Name) }

测试,发送Post请求

 查看程序的执行结果

admin
xxx
原文地址:https://www.cnblogs.com/chadiandianwenrou/p/14110148.html