Muy buenas, soy Miguel y hoy les traigo un artÃculo.
Índice
Estos módulos de Go le ahorrarán mucho tiempo
Go es un lenguaje increÃblemente poderoso y versátil para múltiples propósitos. Es confiable, rápido y fácil de usar.
Golang tiene una documentación fantástica. Go también es muy fácil de escalar . Hoy, analizamos los mejores módulos de Go para facilitar aún más el trabajo con Go. ¡Aquà hay una lista de 10 módulos útiles de Go!
Gen
Gen es una herramienta que realmente genera código para ti, ¿Qué tan útil? Está destinado a ofrecer una funcionalidad similar a los genéricos en sus tipos.
Ejecute el siguiente comando:
go get github.com/clipperhouse/gen
Para utilizar este módulo, primero cree un nuevo proyecto de Go y defina un tipo:
// +gen slice:"Where,Count,GroupBy[string]" type MyType struct {}
Y en la lÃnea de comando, simplemente escriba:
gen
DeberÃa ver un nuevo archivo, llamado mytype_slice.go
Go Kit
Go Kit es una biblioteca estándar para microservicios relacionados con Go. Ofrece soporte para microservicios especializados .
Ejecute el siguiente comando:
go get github.com/go-kit/kit
Vamos a crear un nuevo proyecto de Go y crearemos un nuevo modelo, estamos creando un artÃculo. Ingrese las siguientes lÃneas de código:
// model.go package articleimport ( "time" )// Article model type Article struct { ID string `json:"id"` Username string `json:"username"` Content string `json:"content"` Text string `json:"title"` CreatedOn time.Time `json:"created_on"` }
Ahora necesitamos crear nuestro servicio.
// service.go package articleimport ( "context" )// ArticleService for Articles type TodoService interface { GetAllForUser(ctx context.Context, username string) ([]Article, error) GetByID(ctx context.Context, id string) (Article, error) Add(ctx context.Context, article Article) (Article, error) Update(ctx context.Context, id string, article Article) error Delete(ctx context.Context, id string) error }
Para obtener más información sobre cómo implementar este servicio, le recomendaré que visite Microservicios con GoKit.
Borroso
Ir a la biblioteca que proporciona coincidencias de cadenas difusas optimizadas para nombres de archivo y sÃmbolos de código.
Ejecute el siguiente comando:
go get github.com/jroimartin/gocui
En la página de GitHub de Fuzzy se ha proporcionado este código de ejemplo:
package main import ( "fmt" "github.com/sahilm/fuzzy" ) func main() { const bold = "\033[1m%s\033[0m" pattern := "mnr" data := []string{"game.cpp", "moduleNameResolver.ts", "my name is_Ramsey"} matches := fuzzy.Find(pattern, data) for _, match := range matches { for i := 0; i < len(match.Str); i++ { if contains(i, match.MatchedIndexes) { fmt.Print(fmt.Sprintf(bold, string(match.Str[i]))) } else { fmt.Print(string(match.Str[i])) } } fmt.Println() } } func contains(needle int, haystack []int) bool { for _, i := range haystack { if needle == i { return true } } return false }
Y para una documentación detallada GoDoc.
Etcd
Etcd es un almacén de valor clave distribuido confiable.
Ejecute el siguiente comando:
go get github.com/etcd-io/etcd
Crear cliente usando `clientv3.New`
:
// expect dial time-out on ipv4 blackhole _, err := clientv3.New(clientv3.Config{ Endpoints: []string{"http://254.0.0.1:12345"}, DialTimeout: 2 * time.Second, }) // etcd clientv3 >= v3.2.10, grpc/grpc-go >= v1.7.3 if err == context.DeadlineExceeded { // handle errors } // etcd clientv3 <= v3.2.9, grpc/grpc-go <= v1.2.1 if err == grpc.ErrClientConnTimeout { // handle errors } cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { // handle error! } defer cli.Close()
Para obtener más información sobre cómo utilizar este módulo algo más avanzado, debe consultar el documentos oficiales.
Ginkgo
Ginkgo es un marco de prueba de desarrollo impulsado por el comportamiento. Le permite escribir sus pruebas en una sintaxis que se asemeja al idioma inglés.
Ejecute el siguiente comando:
go get github.com/onsi/ginkgo/ginkgo
Crea un nuevo proyecto de Go. Por ejemplo, importe el paquete gomega en su código de prueba:
package books_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestBooks(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Books Suite") }
Gracias por leer este artÃculo.
Añadir comentario