This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

When sun Wukong was king in the Mountain of Flowers and fruits, he went to the East China Sea specially, where he found the golden hoop stick of Ruyi. Because as a mountain king, how can not have a weapon in hand?

As programmers, we are constantly replenishing our Arsenal in addition to our sidearm, Ctrl C + V. Control C + V should not only be advanced, but also be used properly.

Today we introduce three small tools that can turn JSON, YAML and table into Go struct respectively. The next time you encounter such a conversion scene, you will no longer have to frown and scratch your head.

The first two are converted directly online, and the last requires a library to be installed, but it’s also convenient.

json-to-go

Address: mholt. Making. IO/json – to – go /

Input:

[{"input_index": 0."candidate_index": 0."delivery_line_1": "1 N Rosedale St"."components": {
			"primary_number": "1"."street_predirection": "N"."street_name": "Rosedale"."street_suffix": "St"."city_name": "Baltimore"."state_abbreviation": "MD"}}]Copy the code

Output:

type AutoGenerated []struct {
	InputIndex     int    `json:"input_index"`
	CandidateIndex int    `json:"candidate_index"`
	DeliveryLine1  string `json:"delivery_line_1"`
	Components     struct {
		PrimaryNumber      string `json:"primary_number"`
		StreetPredirection string `json:"street_predirection"`
		StreetName         string `json:"street_name"`
		StreetSuffix       string `json:"street_suffix"`
		CityName           string `json:"city_name"`
		StateAbbreviation  string `json:"state_abbreviation"`
	} `json:"components"`
}
Copy the code

yaml-to-go

Address: ZHWT. Making. IO/yaml – to – go /

Input:

image: golang:latest

before_script:
  - mkdir -p $GOPATH/src/$(dirname $REPO_NAME)
  - ln -svf $CI_PROJECT_DIR $GOPATH/src/$REPO_NAME
  - cd $GOPATH/src/$REPO_NAME

stages:
  - test
  - build
  - deploy

format:
  stage: test
  script:
    - go fmt $(go list . /... | grep -v /vendor/)
    - go vet $(go list . /... | grep -v /vendor/)
    - go test -race $(go list . /... | grep -v /vendor/)
Copy the code

Output:

type AutoGenerated struct {
	Image        string   `yaml:"image"`
	BeforeScript []string `yaml:"before_script"`
	Stages       []string `yaml:"stages"`
	Format       struct {
		Stage  string   `yaml:"stage"`
		Script []string `yaml:"script"`
	} `yaml:"format"`
}
Copy the code

table-to-go

Address github.com/gohouse/con…

Consider a table like this:

CREATE TABLE `prefix_user` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Email` varchar(32) NOT NULL DEFAULT ' ' COMMENT 'email',
  `Password` varchar(32) NOT NULL DEFAULT ' ' COMMENT 'password',
  `CreatedAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP.PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User table'
Copy the code

There are two ways to use it, which are command line invocation and write Go code:

Command line invocation

1, download the corresponding platform executable file, download address: github.com/gohouse/con…

2. Command line execution:

/table2struct-linux.v0.0.3. bin-file model. go-dsn xxx-table userCopy the code

3. Parameter description:

- DSN string database DSN configuration -enableJsonTag bool whether to add json tag -file string saving path -packageName string packageName -prefix string table prefix -realNameMethod Indicates the table name corresponding to the string structure. - Table string Indicates the table to be migrated. -tagKey String Indicates the key of the tagCopy the code

Go code call

Install the library:

go get github.com/gohouse/converter
Copy the code

Code:

package main

import (
	"fmt"
	"github.com/gohouse/converter"
)

func main(a) {
	/ / initialization
	t2t := converter.NewTable2Struct()
	// Personalized configuration
	t2t.Config(&converter.T2tConfig{
		// If the first letter of the field is uppercase, the tag is not added. By default false is added, and true is not added
		RmTagIfUcFirsted: false.// If the field name of the tag is converted to lowercase, the default value is false
		TagToLower: false.// Convert the first letter of the field to lowercase while converting other letters to lowercase. The default value is false
		UcFirstOnly: false.//// put each struct in a separate file, default false, put it in the same file (not provided yet)
		//SeperatFile: false,
	})
	// Start the migration transformation
	err := t2t.
		If you do not specify a table, all tables are migrated by default
		Table("user").
		/ / table prefix
		Prefix("prefix_").
		// Whether to add the JSON tag
		EnableJsonTag(true).
		// Generate the struct name (default: package Model)
		PackageName("model").
		// The key value of the tag field is orm by default
		TagKey("orm").
		// Whether to add a structure method to get the table name
		RealNameMethod("TableName").
		// The path to save the generated structure
		SavePath("/Users/fizz/go/src/github.com/gohouse/gupiao/model/model.go").
		// database DSN, which can be replaced by t2t.db (), taking * sql.db objects
		Dsn("root:root@tcp(localhost:3306)/test? charset=utf8").
		/ / execution
		Run()
	
	fmt.Println(err)
}
Copy the code

Output:

package model

import "time"

type User struct {
	Id         int     `json:"Id" orm:"Id"`
	Email      string  `json:"Email" orm:"Email"`           / / email
	Password   string  `json:"Password" orm:"Password"`     / / password
	CreatedAt  string  `json:"CreatedAt" orm:"CreatedAt"`
}

func (*User) TableName(a) string {
	return "user"
}
Copy the code

Collection!!!! I hope you’ll remember it when you use it.


The brain map and source code in the article are uploaded to GitHub, students who need to download.

Address: github.com/yongxinz/go…

List of Go columns:

  1. Development environment setup and VS Code development tools configuration

  2. Declaration and assignment of variables and constants

  3. Basic data types: integer, floating point, complex, Boolean, and string

  4. Composite data types: array and slice

  5. Composite data types: dictionary map and struct

  6. Process control, catch all

  7. The function thing