| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "embed" |
| 5 | "encoding/json" |
| 6 | "io/fs" |
| 7 | "net/http" |
| 8 | "time" |
| 9 | |
| 10 | "golang.org/x/net/websocket" |
| 11 | |
| 12 | "github.com/gosuda/portal-tunnel/v2/sdk" |
| 13 | ) |
| 14 | |
| 15 | //go:embed static |
| 16 | var staticFiles embed.FS |
| 17 | |
| 18 | func newHandler() http.Handler { |
| 19 | staticFS, _ := fs.Sub(staticFiles, "static") |
| 20 | |
| 21 | mux := http.NewServeMux() |
| 22 | mux.Handle("/", http.FileServer(http.FS(staticFS))) |
| 23 | mux.HandleFunc("/api/ping", handlePing) |
| 24 | mux.Handle("/ws", websocket.Handler(handleWebSocket)) |
| 25 | mux.HandleFunc("/api/test-cookies", handleCookies) |
| 26 | |
| 27 | return mux |
| 28 | } |
| 29 | |
| 30 | func handlePing(w http.ResponseWriter, _ *http.Request) { |
| 31 | w.Header().Set("Content-Type", "application/json") |
| 32 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 33 | "message": "pong", |
| 34 | "time": time.Now().UTC().Format(time.RFC3339), |
| 35 | }) |
| 36 | } |
| 37 | |
| 38 | func handleWebSocket(conn *websocket.Conn) { |
| 39 | defer conn.Close() |
| 40 | for { |
| 41 | var msg string |
| 42 | if err := websocket.Message.Receive(conn, &msg); err != nil { |
| 43 | return |
| 44 | } |
| 45 | if err := websocket.Message.Send(conn, "echo: "+msg); err != nil { |
| 46 | return |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func handleCookies(w http.ResponseWriter, r *http.Request) { |
| 52 | secure := r != nil && r.TLS != nil |
| 53 | |
| 54 | for _, cookie := range []*http.Cookie{ |
| 55 | {Name: "session_id", Value: "abc123", Path: "/", MaxAge: 3600, Secure: secure}, |
| 56 | {Name: "auth_token", Value: "secret456", Path: "/", MaxAge: 3600, Secure: secure}, |
| 57 | {Name: "csrf_token", Value: "xyz789", Path: "/", MaxAge: 3600, Secure: secure}, |
| 58 | {Name: "user_pref", Value: "dark_mode", Path: "/", MaxAge: 86400, Secure: secure}, |
| 59 | } { |
| 60 | http.SetCookie(w, cookie) |
| 61 | } |
| 62 | w.Header().Set("Content-Type", "application/json") |
| 63 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 64 | "message": "4 cookies set: session_id, auth_token, csrf_token, user_pref", |
| 65 | }) |
| 66 | } |
| 67 | |
| 68 | func newUDPInfoHandler(exposure *sdk.Exposure) http.Handler { |
| 69 | mux := http.NewServeMux() |
| 70 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 71 | w.Header().Set("Content-Type", "application/json") |
| 72 | udpAddrs, _ := exposure.WaitDatagramReady(r.Context()) |
| 73 | _ = json.NewEncoder(w).Encode(map[string]any{ |
| 74 | "message": "demo-udp is running", |
| 75 | "udp_addrs": udpAddrs, |
| 76 | }) |
| 77 | }) |
| 78 | return mux |
| 79 | } |