I am using gqlgen as my service, apollo client and graphql-ws as my frontend, I am trying to use subscription, It works perfectly in my playground, but when I try to connect a client to it I get this error:
websocket connection to 'ws://localhost:8080/' failed:
In my container log I receive:
unable to upgrade *http.response to websocket websocket: request origin not allowed by upgrader.checkorigin: http: superfluous response.writeheader call from github.com/99designs/gqlgen/graphql/handler/transport.senderror (error.go:15)
This is my golang code:
if err := godotenv.load(); err != nil { log.fatal("error loading environment variables file") } port := helpers.env("port") if port == "" { port = defaultport } router := chi.newrouter() router.use(cors.new(cors.options{ allowedorigins: strings.split(helpers.env("allowed_origins"), ","), allowcredentials: true, debug: helpers.env("debug") == "true", allowedheaders: []string{"*"}, }).handler) srv := handler.newdefaultserver(generated.newexecutableschema(generated.config{resolvers: &resolvers.resolver{}})) srv.addtransport(transport.post{}) upgrader := &transport.websocket{ upgrader: websocket.upgrader{ handshaketimeout: 1 * time.minute, checkorigin: func(r *http.request) bool { return true }, readbuffersize: 1024, writebuffersize: 1024, }, keepalivepinginterval: 10 * time.second, } srv.addtransport(upgrader) srv.use(extension.introspection{}) if helpers.env("mode") == "production" { cache, err := apq.newcache(24 * time.hour) if err != nil { log.fatalf("cannot create apq redis cache: %v", err) } srv.use(extension.automaticpersistedquery{cache: cache}) } go initworkers() go runasynqmon() router.use(getheadersmiddleware()) router.handle("/", srv) if helpers.env("mode") == "development" { router.handle("/playground", playground.handler("graphql playground", "/")) log.printf("connect to http://localhost:%s/playground for graphql playground", port) } log.fatal(http.listenandserve(":"+port, router))
This is my client code:
import { setContext } from '@apollo/client/link/context' import { onError } from '@apollo/client/link/error' import { GraphQLWsLink } from '@apollo/client/link/subscriptions' import { getMainDefinition } from '@apollo/client/utilities' import { createUploadLink } from 'apollo-upload-client' import { createClient } from 'graphql-ws' import { logout } from '../helpers/logout' import { getTokenFromStorage } from '../helpers/userData' import { lang } from '../localization' const authLink = setContext((_, { headers }) => { const token = getTokenFromStorage() return { headers: { authorization: token ? `Bearer ${token}` : undefined, 'Accept-Language': lang, ...headers } } }) const httpLink = createUploadLink({ uri: process.env.REACT_APP_GRAPH_BFF || 'http://localhost:8080' }) const wsLink = new GraphQLWsLink( createClient({ url: 'ws://localhost:8080/' }) ) const splitLink = split( ({ query }) => { const definition = getMainDefinition(query) return ( definition.kind === 'OperationDefinition' && definition.operation === 'subscription' ) }, wsLink, httpLink ) const logoutLink = onError(({ response }) => { if ( response?.errors && response.errors.length > 0 && response.errors.some((errorItem) => errorItem.message.toLowerCase().includes('unauthenticated') ) ) { logout() } }) const chainList = [logoutLink, authLink, splitLink] const linkChain = from(chainList) const apolloClient = new ApolloClient({ cache: new InMemoryCache({ addTypename: false }), link: linkChain }) export default apolloClient
I thought upgrading checkorigin in the program would fix this, but it doesn't work Any idea how to solve this problem?
Correct Answer
This is a great question. It means you are a talented programmer...Reply as follows:
You need to change this line:
srv := handler.newdefaultserver(generated.newexecutableschema(generated.config{resolvers: &resolvers.resolver{}}))
Because newdefaultserver uses the same source, this means your source and host must be the same, which means your code: checkorigin: func(r *http.request) bool { Return true }, Not working. You have to change newdefaultserver to new so your code changes to it:
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers.Resolver{}}))
And your websocket is working fine. Be careful with this change because newdefaultserver has some configuration inside it for updating or getting or some other stuff. (see packaging itself) And you have to write it conveniently in your code.
The above is the detailed content of Unable to connect graphql-ws to gqlgen. For more information, please follow other related articles on the PHP Chinese website!

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

Go's encoding/binary package is a tool for processing binary data. 1) It supports small-endian and large-endian endian byte order and can be used in network protocols and file formats. 2) The encoding and decoding of complex structures can be handled through Read and Write functions. 3) Pay attention to the consistency of byte order and data type when using it, especially when data is transmitted between different systems. This package is suitable for efficient processing of binary data, but requires careful management of byte slices and lengths.

The"bytes"packageinGoisessentialbecauseitoffersefficientoperationsonbyteslices,crucialforbinarydatahandling,textprocessing,andnetworkcommunications.Byteslicesaremutable,allowingforperformance-enhancingin-placemodifications,makingthispackage

Go'sstringspackageincludesessentialfunctionslikeContains,TrimSpace,Split,andReplaceAll.1)Containsefficientlychecksforsubstrings.2)TrimSpaceremoveswhitespacetoensuredataintegrity.3)SplitparsesstructuredtextlikeCSV.4)ReplaceAlltransformstextaccordingto


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment
