2018-07-07 23:14

GoLang GraphQL显示EOF


Im trying to made a simple GO Server that run with GraphQL and connects with PostgreSQL, the compilation and execution of the files goes well, and the connection to the database also goes well, but when i try to retrieve all the users in the DB, i always get an EOF, viewing for an answer i found

this: Unexpected <EOF> while using graphql

however the answer doesn't fit well with my current project.

This is all the files that go run.


package database

import (

    _ ""

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "lacb2208"
    dbname   = "IMOX_Tech_Personal"

var database *sql.DB

func init() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    var err error
    database, err = sql.Open("postgres", psqlInfo)
    if err != nil {

type User struct {
    ID       int32  `json:"id"`
    UserName string `json:"username"`

// UserData is for params
type UserData struct {
    UserName string

func AllUsers(wrapper func(user *User)) {
    res, err := database.Query("SELECT id_user, username  FROM public.users")
    if err != nil {
        log.Println("error fetching all users", err)
    defer res.Close()
    for res.Next() {
        user := User{}
        if err := res.Scan(&user.ID, &user.UserName); err != nil {


package resolvers

import (

type Resolver struct{}

type UserResolver struct {
    usr *database.User

// UserDataResolver is a struct for Resolver of the User params
type UserDataResolver struct {
    userData *database.UserData

func (r *Resolver) AllUsers() *[]*UserResolver {
    var users []*UserResolver
    wrapper := func(user *database.User) {
        users = append(users, &UserResolver{user})


    return &users

func (userR *UserResolver) ID() int32 {
    return userR.usr.ID

func (userR *UserResolver) UserName() string {
    return userR.usr.UserName


package main

import (





var (
    schema *graphql.Schema

const (
    schemaGraphQL         = "schema.graphqls"
    contentTypeKey        = "Content-Type"
    contentTypeJSONValue  = "application/json"
    authorizationTokenKey = "AuthorizationToken"

type (
    Authorization struct {
        Status             string `json:"status"`
        Message            string `json:"message"`
        AuthorizationToken string `json:"authorization_token`

func init() {
    schemaFile, err := ioutil.ReadFile(schemaGraphQL)
    if err != nil {
    schema = graphql.MustParseSchema(string(schemaFile), &resolvers.Resolver{})

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", getToken)
    router.Handle("/graphiql", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    router.Handle("/query", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        next := &relay.Handler{Schema: schema}
        // authorization := r.Header.Get(authorizationKey)
        // token := strings.Replace(authorization, "Bearer ", "", 1)
        token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiaGFzaGVkLXBhc3N3b3JkIjoiZmMzZDBjMDAxMTdmZjFjY2FlOWQzMTAzZTU3M2M5YzMiLCJpc3MiOiJsdWNob25ldHZ2In0.o8D2I3UwZzxDCmdLHQiQ4XLBFcADOiPKgeuq_-32Nmk"
        ctx := context.WithValue(r.Context(), authorizationTokenKey, token)
        next.ServeHTTP(w, r.WithContext(ctx))

    fmt.Println("server is running on port 8989")
    server := http.ListenAndServe(":8989", handlers.LoggingHandler(os.Stdout, router))

func getToken(response http.ResponseWriter, request *http.Request) {
    response.Header().Set(contentTypeKey, contentTypeJSONValue)

var page = []byte(`
    <!DOCTYPE html>
            <link href="" rel="stylesheet" />
            <script src=""></script>
            <script src=""></script>
            <script src=""></script>
            <script src=""></script>
            <script src=""></script>
        <body style="width: 100%; height: 100%; margin: 0; overflow: hidden;">
            <div id="graphiql" style="height: 100vh;">Loading...</div>
                function graphQLFetcher(graphQLParams) {
                    return fetch("/query", {
                        method: "post",
                        body: JSON.stringify(graphQLParams),
                        credentials: "include",
                    }).then(function (response) {
                        return response.text();
                    }).then(function (responseBody) {
                        try {
                            return JSON.parse(responseBody);
                        } catch (error) {
                            return responseBody;
                    React.createElement(GraphiQL, {fetcher: graphQLFetcher}),


schema {
  query: Query

type User {
  id: Int!
  username: String!

input UserData {
  id: Int!
  userName: String!

type Query {
    allUsers: [User]

type Mutation {
    addUser(userData: UserData!): User

And why not the users table from the database:

CREATE TABLE public.users
  id_user integer NOT NULL DEFAULT nextval('users_id_user_seq'::regclass),
  username character varying(200) NOT NULL,
  password character varying(300) NOT NULL,
  hashed_password character varying(300) NOT NULL,
  status boolean NOT NULL DEFAULT true,
  CONSTRAINT users_pkey PRIMARY KEY (id_user),
  CONSTRAINT users_username_key UNIQUE (username)
ALTER TABLE public.users
  OWNER TO postgres;

The only answer that i get from the server when i run localhost:8989/query is EOF but there's no return of the user list from the database

Please can anyone tell me what im doing wrong in my code...

Or maybe how to do a good query :(

root@Crdzbird-Host:~/GoProjects/go-graphql-sample# curl -XPOST -d '{"query": "{ allUsers{} }"}' localhost:8989/query {"errors":[{"message":"Field \"allUsers\" of type \"[User]\" must have a selection of subfields. Did you mean \"allUsers { ... }\"?","locations":[{"line":1,"column":3}]}]}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doulue1949 doulue1949 3年前

    Everything was fine, my problem was that i wanna access the result via Browser, but when i type in the terminal this:

    root@Crdzbird-Host:~/curl -X POST -H "Content-Type: application/json" -d '{"query": "{ allUsers {id,username} }"}' http://localhost:8989/query

    the values that i get are:


    I was doing the query in the wrong way, thanks for all your support :)

    点赞 评论 复制链接分享