1

I installed golang and started with this tutorial: https://www.howtographql.com/graphql-go/1-getting-started/

When I run:

go run github.com/99designs/gqlgen generate 

I get:

reloading module info
generating core failed: unable to load github.com/my-user/hackernews/graph/model - make sure you're using an import path to a package that exists
exit status 1

What is wrong with my setup? This is my gopath

/Users/my-pc-user/go
DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • have you installed the module? something like `go install github.com/99designs/gqlgen`. Or used go get, outside a module so that its fetched into you default gopath. – The Fool Feb 20 '22 at 19:08
  • Yes, I installed it, and also the init worked. It seems it's unable to load my own local project (named it with github.com) – DenCowboy Feb 20 '22 at 19:13
  • init would always work. It just creates a go mod. but this generator tries to use a module and that module needs to be in your system. Did you add `$HOME/go/bin` to your path? Althogh usually compiled binaries with go install end up there. I think this one needs to be in src. – The Fool Feb 20 '22 at 19:17
  • if you have installed it can use use it as binary? `gqlgen generate` – The Fool Feb 20 '22 at 19:18

1 Answers1

0

TLDR

$ cd your_project_path/
$ print '// +build tools\npackage tools\nimport _ "github.com/99designs/gqlgen"' | gofmt > ./tools.go
$ echo 'package model' | gofmt > ./graph/model/doc.go
$ go get .

Explanation

According to a quick start guide, you should create a package with generated code that actually is already imported by your server:

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/99designs/gqlgen/graphql/handler"
    "github.com/99designs/gqlgen/graphql/playground"
    "your_module_name/graph"
    "your_module_name/graph/generated"
)

Because of the fact that your_module_name/graph/generated has no *.go files you cannot start a server and if you try you will get an error like:

graph/schema.resolvers.go:10:2: no required module provides package your_module_name/graph/generated; to add it:

To generate that package you will need to execute go run github.com/99designs/gqlgen generate, but there is another problem: gqlgen generates code that uses another package that is still doesn't exist yet, i.e. your_module_name/graph/model.

Additional step adding build constraints is required to not drop indirect dependency while generation process. That's why there is the first step with underscore import.

And if you put any *.go file to that directory with package directive — everything should works now:

$ cd your_project_path/
$ print '// +build tools\npackage tools\nimport _ "github.com/99designs/gqlgen"' | gofmt > ./tools.go
$ echo 'package model' | gofmt > ./graph/model/doc.go
$ go get .
zerospiel
  • 632
  • 8
  • 20