Skip to content

Instantly share code, notes, and snippets.

@SemanticallyNull
Last active March 28, 2022 20:25
Show Gist options
  • Save SemanticallyNull/71818e1da066a41b0aa62cf5839ebaf0 to your computer and use it in GitHub Desktop.
Save SemanticallyNull/71818e1da066a41b0aa62cf5839ebaf0 to your computer and use it in GitHub Desktop.
Colour & Morse HTTP
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os/signal"
"strings"
"syscall"
"time"
)
var colors = []int{36, 35, 37, 35, 36, 0}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
r := http.NewServeMux()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Request from %s using %s\n", r.Header.Get("X-Forwarded-For"),
r.Header.Get("User-Agent"))
w.WriteHeader(http.StatusOK)
for idx, char := range strings.Split("Hello, world!\n\n", "") {
fmt.Fprintf(w, "\033[40;%dm%s\033[0m", colors[idx%len(colors)], char)
time.Sleep(100 * time.Millisecond)
w.(http.Flusher).Flush()
}
fmt.Fprintln(w, "Source: https://gist.github.com/SemanticallyNull/71818e1da066a41b0aa62cf5839ebaf0")
})
r.HandleFunc("/morse", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Request from %s using %s\n", r.Header.Get("X-Forwarded-For"),
r.Header.Get("User-Agent"))
w.WriteHeader(http.StatusOK)
for _, char := range strings.Split(".... . .-.. .-.. --- --..-- / .-- --- .-. .-.. -.. -.-.--", "") {
var bell = ""
switch char {
case ".":
bell = "\a"
case "-":
bell = "\a\a"
}
fmt.Fprintf(w, "%s%s", bell, char)
switch char {
case ".":
time.Sleep(100 * time.Millisecond)
case "-":
time.Sleep(200 * time.Millisecond)
default:
time.Sleep(500 * time.Millisecond)
}
w.(http.Flusher).Flush()
}
fmt.Fprintln(w, "\n\nSource: https://gist.github.com/SemanticallyNull/71818e1da066a41b0aa62cf5839ebaf0")
})
srv := &http.Server{
Handler: r,
}
go func() {
l, err := net.Listen("unix", "/tmp/gipwhizz.socket")
if err != nil {
panic(err)
return
}
if err = srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {
panic(err)
return
}
}()
<-ctx.Done()
if err := srv.Shutdown(ctx); err != nil {
fmt.Println("Server forced to shutdown")
return
}
fmt.Println("Server exiting")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment