构建简单服务器

package main


import (
    "fmt"
    "log"
    "net/http"
)


func formHandler(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseForm(); err != nil {
        fmt.Fprintf(w, "ParseForm() err: %v", err)
        return
    }
    fmt.Fprintf(w, "POST Request successful")
    name := r.FormValue("name")
    address := r.FormValue("address")
    fmt.Fprintf(w, "name = %s\n", name)
    fmt.Fprintf(w, "address = %s\n", address)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/hello" {
        http.Error(w, "404 not found", http.StatusNotFound)
        return
    }
    if r.Method != "GET" {
        http.Error(w, "method is not supported", http.StatusMethodNotAllowed)
        return
    }
    fmt.Fprintf(w, "Hello")
}
func main() {
    // 静态资源
    fileServer := http.FileServer(http.Dir("./static"))
    http.Handle("/", fileServer)
    http.HandleFunc("/form", formHandler)
    http.HandleFunc("/hello", helloHandler)
    fmt.Printf("listening on port 8080... \n")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

  转载请注明: malred-blog 构建简单服务器

  目录