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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM