Created
November 18, 2024 04:37
-
-
Save joerx/3c1f4baeaae0b3bec3b1df83adf84bff to your computer and use it in GitHub Desktop.
Basic Golang HTTP Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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