简体   繁体   English

GoLang GraphQL显示EOF

[英]GoLang GraphQL display 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 我试图制作一个运行简单的GraphQL并与PostgreSQL连接的GO Server,文件的编译和执行正常,与数据库的连接也正常,但是当我尝试检索数据库中的所有用户时,我总是得到EOF,查看找到的答案

this: Unexpected <EOF> while using graphql this: 使用graphql时出现意外的<EOF>

however the answer doesn't fit well with my current project. 但是答案并不适合我当前的项目。

This is all the files that go run. 这是所有要运行的文件。

DB.GO 数据库

package database

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

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 {
        log.Fatal(err)
    }
}

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 {
            log.Fatal(err)
        }
        wrapper(&user)
    }
}

RESOLVERS.GO 决议

package resolvers

import (
    "../database"
)

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})
    }

    database.AllUsers(wrapper)

    return &users
}

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

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

MAIN.GO MAIN.GO

package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"

    "github.com/gorilla/mux"

    "./resolvers"

    "github.com/graph-gophers/graphql-go"
    "github.com/graph-gophers/graphql-go/relay"
)

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 {
        panic(err)
    }
    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) {
        w.Write(page)
    }))

    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))
    log.Fatal(server)
}

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

var page = []byte(`
    <!DOCTYPE html>
    <html>
        <head>
            <link href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.css" rel="stylesheet" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-promise/4.1.1/es6-promise.auto.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.js"></script>
        </head>
        <body style="width: 100%; height: 100%; margin: 0; overflow: hidden;">
            <div id="graphiql" style="height: 100vh;">Loading...</div>
            <script>
                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;
                        }
                    });
                }
                ReactDOM.render(
                    React.createElement(GraphiQL, {fetcher: graphQLFetcher}),
                    document.getElementById("graphiql")
                );
            </script>
        </body>
    </html>
    `,
)

and SCHEMA.GRAPHQL SCHEMA.GRAPHQL

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)
)
WITH (
  OIDS=FALSE
);
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 我在运行localhost:8989 / query时从服务器获得的唯一答案是EOF,但没有从数据库返回用户列表

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}]}]} root @ Crdzbird-Host:〜/ GoProjects / go-graphql-sample#curl -XPOST -d'{“ query”:“ {allUsers {}}”}''localhost:8989 / query {“ errors”:[{“ message “:”类型为“ [User] \\”的字段\\“ allUsers \\”必须具有子字段的选择。您是说\\“ allUsers {...} \\”?“,”位置“:[{” line“ :1,“列”: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 root @ Crdzbird-Host:〜/ curl -X POST -H“ Content-Type:application / json” -d'{“ query”:“ {allUsers {id,username}}”}' http:// localhost:8989 /查询

the values that i get are: 我得到的价值是:

{"data":{"allUsers":[{"id":1,"username":"Luis"},{"id":2,"username":"Jean"},{"id":3,"username":"Erich"},{"id":4,"username":"Marcos"},{"id":5,"username":"Alvin"},{"id":6,"username":"Jimmy"}]}} {“ data”:{“ allUsers”:[{“ id”:1,“ username”:“ Luis”},{“ id”:2,“ username”:“ Jean”},{“ id”:3, “ username”:“ Erich”},{“ id”:4,“ username”:“ Marcos”},{“ id”:5,“ username”:“ Alvin”},{“ id”:6,“ username “:”吉米“}]}}

I was doing the query in the wrong way, thanks for all your support :) 我以错误的方式进行查询,感谢您的支持:)

相当于猫&lt; <eof in golang< div><div id="text_translate"><p> 我正在尝试执行等效的操作:</p><pre> cat &lt;&lt;EOF | kubectl apply -f - apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:${reg_port}" EOF</pre><p> 在戈朗。</p><p> 我目前的尝试归结为:</p><pre> func generateConfig(port string) string { return ` apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:" + port` } func main() { exec.Command("kubectl", "apply", "-f", "-", generateConfig(5000)) }</pre><p> 发现它不起作用并出现错误,我并不感到特别惊讶:</p><pre> error: Unexpected args: [ apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:5000"]</pre><p> 我认识到我将这些作为 args 传递并且 kubectl 需要一个文件,但是我发现自己完全不知道如何继续。</p><p> 我宁愿不制作临时文件或调用单独的 bash 脚本,因为这看起来比我希望的必要要复杂。</p></div></eof> - Equivalent to cat <<EOF in golang

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Golang意外的EOF - Golang unexpected EOF 相当于猫&lt; <eof in golang< div><div id="text_translate"><p> 我正在尝试执行等效的操作:</p><pre> cat &lt;&lt;EOF | kubectl apply -f - apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:${reg_port}" EOF</pre><p> 在戈朗。</p><p> 我目前的尝试归结为:</p><pre> func generateConfig(port string) string { return ` apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:" + port` } func main() { exec.Command("kubectl", "apply", "-f", "-", generateConfig(5000)) }</pre><p> 发现它不起作用并出现错误,我并不感到特别惊讶:</p><pre> error: Unexpected args: [ apiVersion: v1 kind: ConfigMap metadata: name: testMap namespace: default data: details: host: "localhost:5000"]</pre><p> 我认识到我将这些作为 args 传递并且 kubectl 需要一个文件,但是我发现自己完全不知道如何继续。</p><p> 我宁愿不制作临时文件或调用单独的 bash 脚本,因为这看起来比我希望的必要要复杂。</p></div></eof> - Equivalent to cat <<EOF in golang golang:ssh:握手失败:EOF - golang: ssh: handshake failed: EOF 带有嵌套模板的 Golang 意外 EOF - Golang unexpected EOF with nested templates HTTP 请求:带有 graphQL 的 golang? - HTTP requests: golang with graphQL? Golang 中的单元测试 GraphQL - unit testing GraphQL in Golang 使用 golang 在 graphql 中递归 - recursion in graphql using golang 子对象未使用Golang解析graphql - Subobject is not parsed graphql with golang GraphQL Golang 身份验证与 JWT - GraphQL Golang Authentication with JWT 在golang ssh会话关闭中将EOF作为错误获取 - Getting EOF as error in golang ssh session close
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM