帮我用go语言写一个http请求接口
下面是一个简单的示例,使用Go语言的net/http包实现HTTP GET请求接口:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
url := r.URL.Query().Get("url")
if url == "" {
http.Error(w, "Missing url parameter", http.StatusBadRequest)
return
}
resp, err := http.Get(url)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
_, err = w.Write([]byte(fmt.Sprintf("Response Status: %s\n\n", resp.Status)))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write([]byte("Response Body:\n\n"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.ReadFrom(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
http.ListenAndServe(":8080", nil)
}
这个接口接收一个名为"url"的查询参数,用于指定要请求的URL。它将发送一个HTTP GET请求到该URL,并将响应的状态码和正文写回响应中。如果请求失败,则返回一个HTTP 500内部服务器错误
原文地址: https://www.cveoy.top/t/topic/fRD5 著作权归作者所有。请勿转载和采集!