Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Created September 19, 2019 18:00
Show Gist options
  • Select an option

  • Save aquiseb/2d0db8ef79554ae45eaa7a26f230e35d to your computer and use it in GitHub Desktop.

Select an option

Save aquiseb/2d0db8ef79554ae45eaa7a26f230e35d to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
)
type Resolver struct{}
func (*Resolver) Hello() string { return "Hello, world!" }
func main() {
s := `
schema {
query: Query
}
type Query {
hello: String!
}
`
schema := graphql.MustParseSchema(s, &Resolver{})
http.Handle("/graphql", &relay.Handler{Schema: schema})
// Write a GraphiQL page to /
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(page)
}))
log.Fatal(http.ListenAndServe(":4444", nil))
}
//////// GRAPHiQL ////////
var page = []byte(`
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.10.2/graphiql.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/1.1.0/fetch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.10.2/graphiql.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("/graphql", {
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>
`)
@aquiseb

aquiseb commented Sep 19, 2019

Copy link
Copy Markdown
Author

go run main.go

Then visit http://localhost:4444

run this

{
    hello
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment