學習之路 / handle請求

臺北下了雪發表於2021-11-19
package main

import (
    "net/http"
)

type helloHandler struct{}

func (hh *helloHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    rw.Write([]byte("hello world"))
}

type aboutHandler struct{}

func (ah *aboutHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    rw.Write([]byte("About !"))
}

func users(rw http.ResponseWriter, r *http.Request) {
    rw.Write([]byte("users page"))
}

func roles(rw http.ResponseWriter, r *http.Request) {
    rw.Write([]byte("roles page"))
}

func main() {
    hh := new(helloHandler)
    ah := new(aboutHandler)
    server := http.Server{
        Addr:    "localhost:8111",
        Handler: nil,
    }
    http.Handle("/hello", hh)
    http.Handle("/about", ah)
    http.Handle("/roles", http.HandlerFunc(roles))

    http.HandleFunc("/news", func(rw http.ResponseWriter, r *http.Request) {
        rw.Write([]byte("news"))
    })
    http.HandleFunc("/users", users)

    server.ListenAndServe()

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章