使用Go语言编写一个简单的Web框架

  package main

  import (

  "fmt"

  "net/http"

  )

  var routes = map[string]http.HandlerFunc{

  "/": hello,

  "/about": about,

  }

  func main() {

  http.HandleFunc("/", middleware(root))

  http.ListenAndServe(":8080", nil)

  }

  func middleware(next http.HandlerFunc) http.HandlerFunc {

  return func(w http.ResponseWriter, r *http.Request) {

  fmt.Printf("IP Address: %s

  ", r.RemoteAddr)

  next(w, r)

  }

  }

  func root(w http.ResponseWriter, r *http.Request) {

  handler := routes[r.URL.Path]

  if handler != nil {

  handler(w, r)

  } else {

  http.NotFound(w, r)

  }

  }

  func hello(w http.ResponseWriter, r *http.Request) {

  fmt.Fprintf(w, "Hello, World!")

  }

  func about(w http.ResponseWriter, r *http.Request) {

  fmt.Fprintf(w, "About Us")

  }