Table of Contents
Question content
Workaround
Home Backend Development Golang Websocket server implementation using x/net library trowing 403

Websocket server implementation using x/net library trowing 403

Feb 13, 2024 pm 05:03 PM
standard library

使用 x/net 库 trowing 403 的 Websocket 服务器实现

php editor Banana will introduce you to a method using the x/net library to implement a Websocket server that throws a 403 error. Websocket is a communication protocol that establishes a persistent connection between a client and a server, and a 403 error means that the server rejected the client's request. By using the x/net library, we can easily create a Websocket server and reject requests by throwing a 403 error when needed. This method is simple and effective, and is suitable for scenarios where requests need to be authorized or access restricted.

Question content

I am trying to implement a websocket server using the x/net/websocket standard library.

My attempts so far are as follows:

package main

import (
    "fmt"
    "net/http"

    "golang.org/x/net/websocket"
)

type Server struct {
    baseUri     string
    connections map[string][]*websocket.Conn
}

func initServer(baseUri string) *Server {
    return &Server{
        baseUri: baseUri,
    }
}

func (server *Server) handleConnections() {
    http.Handle("/ws", websocket.Handler(server.listenConnections))
    http.ListenAndServe(":3000", nil)
}

func (server *Server) listenConnections(ws *websocket.Conn) {
    fmt.Println("New connection established")
    for {
        fmt.Println("FOO")
    }
}

func main() {
    server := initServer("/ws")
    server.handleConnections()
}

Copy after login

When trying to connect to ws://localhost:3000/ws using multiple ws clients, I always get the same error: 403-Forbidden. I even tried the example from the official documentation but still get it. Am I missing something obvious? Like default port blocking or something like that?

Thank you in advance.

EDIT: You may need to use a different port to reproduce the issue. Using 3000 in my example will just interrupt the execution of the program if it is not available.

Edit 2: You can use a client like websocat and execute websocat 'ws://localhost:3000/ws' to try to connect to the server

Workaround

I gave up, but had good insights: If you're like me and are following Anthony GG's Walkthrough of Creating a Websocket Server on Go from Scratch, don't. Video is outdated, and while it provides a good intuition on how to create videos, it's best (and no shame) to learn using gorilla's websocket library.

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

type Server struct {
    baseUri     string
    connections map[string][]*websocket.Conn
    router      *mux.Router
    setup       *http.Server
}

func initServer(baseUri string) *Server {
    router := mux.NewRouter()
    return &Server{
        baseUri: baseUri,
        router:  router,
        setup: &http.Server{
            Handler:      router,
            Addr:         "127.0.0.1:8000",
            WriteTimeout: 15 * time.Second,
            ReadTimeout:  15 * time.Second,
        },
    }
}

func (server *Server) handleConnections() {
    server.router.HandleFunc("/ws/{var}", server.listenConnections)
    server.setup.ListenAndServe()
}

func (server *Server) listenConnections(w http.ResponseWriter, r *http.Request) {
    connection, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    for {
        _, message, err := connection.ReadMessage()
        if err != nil {
            break
        }

        connection.WriteMessage(websocket.TextMessage, message)
        go messageHandler(message)
    }
    fmt.Println("Out of loop")
}

func messageHandler(message []byte) {
    fmt.Println(string(message))
}

func main() {
    server := initServer("/ws")
    server.handleConnections()
}

Copy after login

I also used gorilla/mux to use path parameters (not sure why the http handler can't). Notice how I changed http.Handle to mux.Router.HandleFunc. As user @Cerise pointed out in the comments, the x/net/websocket package is not in the standard library, but just adding the Origin header didn't solve the original problem either.

Hopefully this saves some of the trouble others like me running into when learning Go.

The above is the detailed content of Websocket server implementation using x/net library trowing 403. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use absolute value in c++ How to use absolute value in c++ May 06, 2024 pm 06:15 PM

There are two ways to obtain absolute values ​​in C++: 1. Use the built-in function abs() to obtain the absolute value of an integer or floating point type; 2. Use the generic function std::abs() to obtain various supported absolute values. Operates on absolute values ​​of data types.

How to use std:: in c++ How to use std:: in c++ May 09, 2024 am 03:45 AM

std is the namespace in C++ that contains components of the standard library. In order to use std, use the "using namespace std;" statement. Using symbols directly from the std namespace can simplify your code, but is recommended only when needed to avoid namespace pollution.

How to pop up a window in python How to pop up a window in python May 05, 2024 pm 08:15 PM

There are two ways to create popups in Python: Tkinter: Use the Tkinter library to create Tk or TopLevel widgets. Pyglet: Use the Pyglet library to create Window windows.

What does prime mean in c++ What does prime mean in c++ May 07, 2024 pm 11:33 PM

prime is a keyword in C++, indicating the prime number type, which can only be divided by 1 and itself. It is used as a Boolean type to indicate whether the given value is a prime number. If it is a prime number, it is true, otherwise it is false.

What does config mean in java? What does config mean in java? May 07, 2024 am 02:39 AM

Config represents configuration information in Java and is used to adjust application behavior. It is usually stored in external files or databases and can be managed through Java Properties, PropertyResourceBundle, Java Configuration Framework or third-party libraries. Its benefits include decoupling and flexibility. , environmental awareness, manageability, scalability.

What does fabs mean in c++ What does fabs mean in c++ May 08, 2024 am 01:15 AM

The fabs() function is a mathematical function in C++ that calculates the absolute value of a floating point number, removes the negative sign and returns a positive value. It accepts a floating point parameter and returns an absolute value of type double. For example, fabs(-5.5) returns 5.5. This function works with floating point numbers, whose accuracy is affected by the underlying hardware.

_complex usage in c language _complex usage in c language May 08, 2024 pm 01:27 PM

The complex type is used to represent complex numbers in C language, including real and imaginary parts. Its initialization form is complex_number = 3.14 + 2.71i, the real part can be accessed through creal(complex_number), and the imaginary part can be accessed through cimag(complex_number). This type supports common mathematical operations such as addition, subtraction, multiplication, division, and modulo. In addition, a set of functions for working with complex numbers is provided, such as cpow, csqrt, cexp, and csin.

How to calculate absolute value in c++ How to calculate absolute value in c++ May 06, 2024 pm 06:21 PM

There are three ways to find the absolute value in C++: Using the abs() function, you can calculate the absolute value of any type of number. Using the std::abs() function, you can calculate the absolute value of integers, floating point numbers, and complex numbers. Manual calculation of absolute values, suitable for simple integers.

See all articles