Skip to content

Embebiendo en apps Go

Busindre edited this page Nov 3, 2016 · 1 revision

Es posible embeber websocketd dentro de un proyecto go existente mediante el registro de un "handler".

Ejemplo:

package main

import (
    "fmt"
    wsd "github.com/joewalnes/websocketd/libwebsocketd"
    "net/http"
)

const MAXFORKS = 10

func main() {
    // A log scope allows you to customize the logging that websocketd performs. 
    //You can provide your own log scope with a log func.
    logScope := wsd.RootLogScope(wsd.LogAccess, func(l *wsd.LogScope, 
        level wsd.LogLevel, levelName string,
        category string, msg string, args ...interface{}) {
        fmt.Println(args...)
    })
    // Configuration options tell websocketd where to look for programs to
    // run as WebSockets.
    config := &wsd.Config{
        ScriptDir:      "./ws-bin",
        UsingScriptDir: true,
        StartupTime:    time.Now(),
        DevConsole:     true,
    }
    // Register your route and handler.
    os.ClearEnv();
    http.HandleFunc("/ws-bin/", func(rw http.ResponseWriter, req *http.Request) {
        handler := http.StripPrefix("/ws-bin", wsd.NewWebsocketdServer(config, logScope, MAXFORKS))
        handler.ServeHTTP(rw, req)
    })
    if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); err != nil {
        fmt.Println("could not start server!", err)
        os.Exit(1)
    }
}

Asegúrese de ejecutar go get para buscar dependencias.

Clone this wiki locally