J'apprends la langue et j'ai encore un peu de connaissances. J'écris http serveur statique (en 1ère phase pour servir les actifs). J'essaye aussi d'utiliser le paquetage gorilla/mux en tant que routeur.go> comment refactoriser http handler from main
Jusqu'à présent, je fini avec
pagekage main
import (
"fmt"
"github.com/gorilla/mux"
"html"
"net/http"
)
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
http.FileServer(http.Dir("public/"))))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
il fonctionne très bien et sert tous les fichiers sous/public/
Maintenant, je voudrais factoriser le code
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
http.FileServer(http.Dir("public/"))))
être en formulaire
r.PathPrefix("/public/").Handler(PublicHandler)
C'est assez basique et j'aimerais apprendre à rendre le code plus beau.
Pouvez-vous nous donner votre avis? THX.
Salut JimB, oui, je sais que je peux faire est que vous avez écrit ci-dessus. Je pense à déplacer PublicHandler: = http.StripPrefix ("/ public /", http.FileServer (http.Dir ("public /"))) à sa propre fonction. Et cette étape me cause des difficultés. – Jaro
@Jaro: S'il vous plaît poster un exemple de ce que vous demandez vraiment. Il n'y a aucune raison que vous ne puissiez pas retourner PublicHandler à partir d'une fonction. – JimB