refactor(go): simplify URL path logic

This commit is contained in:
Guanran Wang 2024-10-19 12:19:03 +08:00
parent 49ca0945fb
commit dd807cb0d3
Signed by: nyancat
GPG key ID: 91F97D9ED12639CF

24
main.go
View file

@ -22,10 +22,18 @@ func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./assets/static"))))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) {
handleRequest(w, r, tmpl)
})
http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `User-Agent: *
Disallow: /harming/humans
Disallow: /ignoring/human/orders
Disallow: /harm/to/self
`)
})
log.Printf("Starting server on %s", config.listen)
log.Fatal(http.ListenAndServe(config.listen, nil))
}
@ -36,9 +44,6 @@ func handleRequest(w http.ResponseWriter, r *http.Request, tmpl *template.Templa
log.Printf("r.URL.Path: %s, sourceIP: %s, isHeadless: %t, User-Agent: %s", r.URL.Path, sourceIP, isHeadless, r.Header.Get("User-Agent"))
// TODO: /favicon.ico
switch r.URL.Path {
case "/":
if isHeadless {
fmt.Fprintf(w, "%s\n", sourceIP)
} else {
@ -63,17 +68,6 @@ func handleRequest(w http.ResponseWriter, r *http.Request, tmpl *template.Templa
return
}
}
case "/robots.txt":
fmt.Fprintf(w, `User-Agent: *
Disallow: /harming/humans
Disallow: /ignoring/human/orders
Disallow: /harm/to/self
`)
default:
http.NotFound(w, r)
}
}
func getEnvOr(key, defaultValue string) string {