add ch13
This commit is contained in:
46
ch13/2/ch13_2.go
Normal file
46
ch13/2/ch13_2.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TimeHandler struct{}
|
||||
|
||||
func (th TimeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(time.Now().Format(time.RFC3339)))
|
||||
}
|
||||
|
||||
func RequestToIP(r *http.Request) string {
|
||||
ip, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
slog.Error(fmt.Sprintf("Wrong format of address: %q", r.RemoteAddr))
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func RequestIPHandler(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Info(RequestToIP(r))
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func main() {
|
||||
server := http.Server{
|
||||
Addr: ":10100",
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 90 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
Handler: RequestIPHandler(TimeHandler{}),
|
||||
}
|
||||
err := server.ListenAndServe()
|
||||
if err != nil {
|
||||
if err != http.ErrServerClosed {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user