Skip to content

Instantly share code, notes, and snippets.

@blinksmith
Last active March 30, 2024 16:58
Show Gist options
  • Save blinksmith/1b905ab4bf7092574ef9 to your computer and use it in GitHub Desktop.
Save blinksmith/1b905ab4bf7092574ef9 to your computer and use it in GitHub Desktop.
Collection of Minimal Go web server
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir(".")))
http.ListenAndServe(":8080", nil)
}
package main
import (
"net/http"
"time"
)
func main() {
srv := &http.Server{
Addr: ":8080",
Handler: http.FileServer(http.Dir(".")),
ReadTimeout: 10 * time.Second,
}
srv.ListenAndServe()
}
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir(".")))
http.ListenAndServe(":8080", mux)
}
package main
import (
"log"
"net/http"
)
type LogRecord struct {
http.ResponseWriter
status int
}
func (r *LogRecord) Write(p []byte) (int, error) {
return r.ResponseWriter.Write(p)
}
func (r *LogRecord) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func WrapHandler(f http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
record := &LogRecord{
ResponseWriter: w,
}
f.ServeHTTP(record, r)
log.Println("Bad Request ", record.status)
if record.status == http.StatusBadRequest {
log.Println("Bad Request ", r)
}
}
}
func main() {
router := http.NewServeMux()
s := &http.Server{
Addr: ":8080",
Handler: WrapHandler(router),
}
log.Fatal(s.ListenAndServe())
}
package main
import (
"os"
"os/signal"
"syscall"
"log"
"net"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir(".")))
server := &http.Server{Handler: mux}
listener, err := net.Listen("tcp", ":8080")
if nil != err {
log.Fatalln(err)
}
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
go server.Serve(listener)
log.Println(<-ch)
listener.Close()
time.Sleep(60e9) // FIXME!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment