Convert a MySQL CREATE TABLE statement to a Go struct with tags:
form, json, and xorm tagsFor complete MySQL to Go type mappings, see type_mappings.md.
MySQLGoNotesINT``int``BIGINT``int64``VARCHAR``string``TEXT``string``DATETIME``time.Time``TIMESTAMP``time.Time``BOOL / BIT(1)``bool``DECIMAL``float64Or custom type
Convert snake_case to CamelCase:
text
user_name → UserName
created_at → CreatedAt
user_id → UserID
api_key → APIKey
is_active → IsActive
Special cases - acronyms remain uppercase:
id → IDurl → URLuri → URIGenerate three tags for each field:
form: HTTP form parameter name (snake_case)json: JSON field name (snake_case)xorm: XORM ORM column name and constraintsConstraintTagPrimary keyxorm:"pk"Auto incrementxorm:"autoincr"Not nullxorm:"not null"Uniquexorm:"unique"Default valuexorm:"default 'value'"Nullablexorm:"nullable"Indexxorm:"index"Commentxorm:"comment 'text'"
Combine constraints: xorm:"'user_id' pk autoincr"
sql
CREATE TABLE users (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL,
age INT DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE,
bio TEXT
) COMMENT='User table';
go
package models
import "time"
// User represents the users table
type User struct {
ID uint64 `form:"id" json:"id" xorm:"'id' pk autoincr"`
Username string `form:"username" json:"username" xorm:"'username' unique not null"`
Email string `form:"email" json:"email" xorm:"'email' not null"`
Age int `form:"age" json:"age" xorm:"'age' default 0"`
CreatedAt time.Time `form:"created_at" json:"created_at" xorm:"'created_at'"`
IsActive bool `form:"is_active" json:"is_active" xorm:"'is_active' default true"`
Bio string `form:"bio" json:"bio" xorm:"'bio'"`
}
For nullable columns (allows NULL), use pointer types:
go
// MySQL: phone VARCHAR(20) NULL
Phone *string `form:"phone" json:"phone" xorm:"'phone' nullable"`
Use table comment as struct comment, or generate from table name:
go
// User represents the users table