./categories/server
Go HTTP 서버·라우팅
1) 기본 서버
package main
import ("io"; "log"; "net/http")
func myServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello world\n")
}
func main() {
http.HandleFunc("/", myServer)
log.Fatal(http.ListenAndServe(":8000", nil))
}
2) 커스텀 멀티플렉서 (ServeHTTP)
type CustomServeMux struct{}
func (p *CustomServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" { giveRandom(w, r); return }
http.NotFound(w, r)
}
mux := &CustomServeMux{}
http.ListenAndServe(":8000", mux)
3) http.NewServeMux
mux := http.NewServeMux()
mux.HandleFunc("/randomFloat", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, rand.Float64())
})
mux.HandleFunc("/randomInt", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, rand.Intn(100))
})
http.ListenAndServe(":8000", mux)
4) httprouter (경로 파라미터)
go get github.com/julienschmidt/httprouter
func showParams(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
fmt.Fprintf(w, params.ByName("name"))
}
router := httprouter.New()
router.GET("/api/v1/go-version", goVersion)
router.GET("/api/v1/t/:name", showParams)
router.ServeFiles("/static/*filepath", http.Dir("d:\\test"))
log.Fatal(http.ListenAndServe(":8000", router))
- 외부 명령 stdout:
os/execCommand(...).Start()/Wait()
5) gorilla/mux (정규식 경로)
go get -u github.com/gorilla/mux
func ArticleHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Fprintf(w, "Category: %v, ID: %v\n", vars["category"], vars["id"])
}
router := mux.NewRouter()
router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
srv := &http.Server{Handler: router, Addr: "127.0.0.1:8000",
WriteTimeout: 15*time.Second, ReadTimeout: 15*time.Second}
log.Fatal(srv.ListenAndServe())
// /articles/books/123 → Category: books, ID: 123
관련 링크: https://github.com/bear2u/til/tree/master/golang/restfulapi
./comments