Programing

Go에 대한 다른 방법의 http 요청을 어떻게 처리 할 수 ​​있습니까?

crosscheck 2020. 11. 2. 07:38
반응형

Go에 대한 다른 방법의 http 요청을 어떻게 처리 할 수 ​​있습니까?


나는 핸들 요청에 가장 좋은 방법 알아 내려고 노력하고 있습니다 //이동에를 다양한 방법으로 다른 방법을 처리합니다. 내가 생각 해낸 최고는 다음과 같습니다.

package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }

        if r.Method == "GET" {
            fmt.Fprintf(w, "GET, %q", html.EscapeString(r.URL.Path))
        } else if r.Method == "POST" {
            fmt.Fprintf(w, "POST, %q", html.EscapeString(r.URL.Path))
        } else {
            http.Error(w, "Invalid request method.", 405)
        }
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

관용적 인 바둑인가요? 이것이 표준 http lib로 할 수있는 최선입니까? 나는 http.HandleGet("/", handler)Express 또는 Sinatra에서 와 같은 것을 훨씬 차라리 할 것 입니다. 간단한 REST 서비스를 작성하기위한 좋은 프레임 워크가 있습니까? web.go 는 매력적으로 보이지만 정체되어 있습니다.

당신의 충고에 감사합니다.


루트 만 제공하려면 : 올바른 일을하고 있습니다. 어떤 경우에는 NotFound를 호출하는 대신 http.FileServer 개체의 ServeHttp 메서드를 호출 할 수 있습니다. 또한 제공하려는 기타 파일이 있는지 여부에 따라 다릅니다.

다른 메서드를 다르게 처리하려면 : 많은 HTTP 처리기에는 다음과 같은 switch 문만 포함되어 있습니다.

switch r.Method {
case http.MethodGet:
    // Serve the resource.
case http.MethodPost:
    // Create a new record.
case http.MethodPut:
    // Update an existing record.
case http.MethodDelete:
    // Remove the record.
default:
    // Give an error message.
}

물론 gorilla와 같은 타사 패키지가 더 잘 작동한다는 것을 알 수 있습니다.


어, 나는 실제로 잠자리에 들었으므로 http://www.gorillatoolkit.org/pkg/mux보는 것에 대한 빠른 의견 은 정말 멋지고 원하는 것을 수행합니다. 문서를 살펴보십시오. 예를 들면

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}

r.HandleFunc("/products", ProductsHandler).
    Host("www.domain.com").
    Methods("GET").
    Schemes("http")

위의 작업을 수행하는 다른 많은 가능성과 방법.

그러나 나는 "이것이 내가 할 수있는 최선인가"라는 질문의 다른 부분을 다룰 필요가 있다고 느꼈다. std lib가 너무 노출 된 경우 확인해야 할 훌륭한 리소스는 https://github.com/golang/go/wiki/Projects#web-libraries (웹 라이브러리에 특별히 링크 됨)입니다.

참고URL : https://stackoverflow.com/questions/15240884/how-can-i-handle-http-requests-of-different-methods-to-in-go

반응형