Search code examples
gographqlgqlgen

Golang: generating core failed: unable to load github.com


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

Solution

  • 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 .