search
HomeBackend DevelopmentGolangUnable to connect graphql-ws to gqlgen

无法将 graphql-ws 连接到 gqlgen

Question content

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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

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.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

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

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

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

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

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.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

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 Binary Encoding/Decoding: A Practical Guide with ExamplesGo Binary Encoding/Decoding: A Practical Guide with ExamplesMay 07, 2025 pm 05:37 PM

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.

Go 'bytes' Package: Compare, Join, Split & MoreGo 'bytes' Package: Compare, Join, Split & MoreMay 07, 2025 pm 05:29 PM

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

Go Strings Package: Essential Functions You Need to KnowGo Strings Package: Essential Functions You Need to KnowMay 07, 2025 pm 04:57 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

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

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment