HTTP Server dengan Serve Mux
Contoh code HTTP server mux dengan handler
package main
import (
"fmt"
"net/http"
)
type HelloHandler struct{}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
type WorldHandler struct{}
func (h *WorldHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "World!")
}
func main() {
var hello http.Handler = &HelloHandler{}
var world http.Handler = &WorldHandler{}
mux := http.NewServeMux()
mux.Handle("/hello", hello)
mux.Handle("/world", world)
server := http.Server{
Addr: "localhost:5000",
Handler: mux,
}
fmt.Printf("Server running on %s", server.Addr)
err := server.ListenAndServe()
if err != nil {
panic(err.Error())
}
}Contoh code HTTP server mux dengan handler func
Last updated