GGenums - Generate Golang Enums
GGenums is a code generation tool that makes working with enums in Go easier and safer. It automatically generates type-safe enums with built-in string conversion, JSON marshaling/unmarshaling, and validation.
Features
- ๐ Simple enum declaration using comments
- ๐ Type-safe enum values
- ๐ฆ JSON marshaling/unmarshaling support
- โ
Built-in validation
- ๐ String conversion methods
- ๐ Easy to read generated code
Installation
go install github.com/Gandalf-Le-Dev/ggenums@latest
[!NOTE]
Make sure you have the go/bin directory in your PATH:
export PATH=$PATH:$(go env GOPATH)/bin
Quick Start
-
Define your enum using a comment:
//enum:name=Status values=pending,active,in_progress,completed
-
Run the generator:
ggenums ./...
-
Use your generated enum:
status := StatusPending
if status.IsValid() {
fmt.Println(status) // Output: pending
}
Example
package main
import (
"encoding/json"
"fmt"
)
//enum:name=Status values=pending,active,in_progress,completed
//enum:name=Role values=admin,user,guest
type User struct {
ID string `json:"id"`
Status StatusEnum `json:"status"`
Role RoleEnum `json:"role"`
}
func main() {
var err error
// JSON marshaling
user := User{
ID: "123",
Status: StatusPending,
Role: RoleAdmin,
}
jsonData, _ := json.Marshal(user)
fmt.Printf("JSON: %s\n", jsonData)
// JSON unmarshaling
var parsed User
json.Unmarshal(jsonData, &parsed)
fmt.Printf("Parsed: %+v\n", parsed)
// Parsing from string
status, _ := ParseStatus("in_progress")
fmt.Printf("Parsed status: %s\n", status)
// Validation
err = status.Validate()
if err != nil {
fmt.Printf("Validation error: %v\n", err)
} else {
fmt.Printf("Status '%s' is valid\n", status)
}
// Comparison
fmt.Printf("Is status in progress? %v\n", status == StatusInProgress)
// Error handling
_, err = ParseStatus("error_status")
fmt.Printf("Invalid status error: %v\n", err)
}
Output:
JSON: {"id":"123","status":"pending","role":"admin"}
Parsed: {ID:123 Status:pending Role:admin}
Parsed status: in_progress
Status 'in_progress' is valid
Is status in progress? true
Invalid status error: invalid Status: error_status
Generated Code Features
The generated code includes:
- Type-safe enum constants
- String conversion methods
- JSON marshaling/unmarshaling
- Validation methods
- Parsing functions
- Slice of all enum values
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.