mkdir go-graphql-todoapi
cd go-graphql-todoapi
go mod init github.com/bryanpinheiro/go-graphql-todoapi
go get gorm.io/gorm
go get gorm.io/driver/sqlite
-
create a tools.go file
//go:build tools // +build tools package tools import ( _ "github.com/99designs/gqlgen" )
-
add the dependency automatically:
go mod tidy
go run github.com/99designs/gqlgen init
-
schema.graphqls:
type Todo { id: Int! title: String! completed: Boolean! } type Query { todo(id: Int!): Todo } schema { query: Query }
-
resolver.go:
package graph import ( "context" "github.com/bryanpinheiro/go-graphql-todoapi/database" "github.com/bryanpinheiro/go-graphql-todoapi/models" ) type Resolver struct{} func (r *Resolver) Todos(ctx context.Context) ([]*models.Todo, error) { // Access the DB instance from the database package db := database.DB var todos []*models.Todo if err := db.Find(&todos).Error; err != nil { return nil, err } return todos, nil }
-
fix some dependencies:
go get github.com/99designs/gqlgen/graphql/handler
go run github.com/99designs/gqlgen generate
go run server.go