|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "github.com/vmware/transport-go/wasm/example/server/render" |
| 7 | + "io/fs" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "os/signal" |
| 12 | + "path" |
| 13 | + "strings" |
| 14 | + "syscall" |
| 15 | +) |
| 16 | + |
| 17 | +func main() { |
| 18 | + sigChan := make(chan os.Signal) |
| 19 | + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGKILL) |
| 20 | + server := exampleServer() |
| 21 | + |
| 22 | + go func() { |
| 23 | + <-sigChan |
| 24 | + server.Shutdown(context.Background()) |
| 25 | + }() |
| 26 | + |
| 27 | + log.Println("example server running at http://localhost:30080") |
| 28 | + _ = server.ListenAndServe() |
| 29 | +} |
| 30 | + |
| 31 | +func exampleServer() *http.Server { |
| 32 | + handler := http.NewServeMux() |
| 33 | + handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 34 | + // template |
| 35 | + tmpl := render.GetTemplate(render.IndexRoute) |
| 36 | + err := tmpl.Execute(w, nil) |
| 37 | + if err != nil { |
| 38 | + http.Error(w, err.Error(), 500) |
| 39 | + } |
| 40 | + }) |
| 41 | + |
| 42 | + handler.HandleFunc("/assets/", func(w http.ResponseWriter, r *http.Request) { |
| 43 | + split := strings.Split(r.RequestURI[1:], "/") |
| 44 | + resourcePath := path.Join("templates", strings.Join(split[1:], "/")) |
| 45 | + b, err := fs.ReadFile(render.FS, resourcePath) |
| 46 | + if err != nil { |
| 47 | + if errors.Is(err, fs.ErrNotExist) { |
| 48 | + http.NotFound(w, r) |
| 49 | + } else { |
| 50 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 51 | + } |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + w.Write(b) |
| 56 | + }) |
| 57 | + |
| 58 | + s := &http.Server{ |
| 59 | + Addr: ":30080", |
| 60 | + Handler: handler, |
| 61 | + } |
| 62 | + |
| 63 | + return s |
| 64 | +} |
0 commit comments