Skip to content

Instantly share code, notes, and snippets.

@joerx
Created November 18, 2024 04:37
Show Gist options
  • Save joerx/3c1f4baeaae0b3bec3b1df83adf84bff to your computer and use it in GitHub Desktop.
Save joerx/3c1f4baeaae0b3bec3b1df83adf84bff to your computer and use it in GitHub Desktop.
Basic Golang HTTP Server
package main
import (
"log"
"net/http"
)
func main() {
handler := &myHandler{}
mux := http.NewServeMux()
mux.Handle("GET /moochis", logger(handler))
mux.Handle("POST /moochi", logger(handler))
mux.Handle("GET /moochi/{name}", logger(handler))
http.ListenAndServe(":3000", mux)
}
type myHandler struct{}
func (myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Request OK"))
}
func logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Request received")
log.Printf("Path: %v", r.URL.Path)
log.Printf("Method: %v", r.Method)
log.Printf("Name: %v", r.PathValue("name"))
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment