当前位置: 首页 > news >正文

golang 实现http请求的调用,访问并读取页面数据和内置的一些方法

下午就不能好好学习一下golang,业务一直找个不停,自己定的业务规则都能忘得一干二净,让你查半天,完全是浪费时间。

golang实现访问并读取页面数据

package mainimport ("fmt""net/http"
)var urls = []string{"http://www.google.com/","http://golang.org/","http://blog.golang.org/",
}
// 使用http.Head方法,如果地址不通,自己换一个,这些是国外的,需要代理或者开加速器才行
func main() {// Execute an HTTP HEAD request for all url's// and returns the HTTP status string or an error string.for _, url := range urls {resp, err := http.Head(url)if err != nil {fmt.Println("Error:", url, err)}fmt.Println(url, ": ", resp.Status)}
}

golang使用http.get

package mainimport ("fmt""io/ioutil""log""net/http"
)func main() {res, err := http.Get("http://www.google.com")checkError(err)// 有些资料这里是ioutil.ReadAll,是因为版本低,高版本的可以改为以下的包路劲data, err := io.ReadAll(res.Body)checkError(err)// 这里会把网页的页面读取打印出来fmt.Printf("Got: %q", string(data))
}func checkError(err error) {if err != nil {log.Fatalf("Get : %v", err)}
}

通过 xml 包将这个状态解析成为一个结构

package mainimport ("encoding/xml""fmt""net/http"
)/*这个结构会保存解析后的返回数据。
他们会形成有层级的 XML,可以忽略一些无用的数据*/
type Status struct {Text string
}type User struct {XMLName xml.NameStatus  Status
}func main() {// 发起请求查询推特 Goodland 用户的状态// 这个地址调不通了,是400,自己换一个其他的response, _ := http.Get("http://twitter.com/users/Googland.xml")// 初始化 XML 返回值的结构user := User{xml.Name{"", "user"}, Status{""}}// 将 XML 解析为我们的结构// 有些资料直接把response.Body放入到xml.Unmarshal中了,由于版本不同,高版本的这里是放入的btye数组,因此使用json方法转了一下byteRes, errorMsg := json.Marshal(response.Body)if errorMsg == nil {xml.Unmarshal(byteRes, &user)fmt.Printf("status: %s", user.Status.Text)}
}

http包中包含了各式各样的函数,方法供我们调用

  • http.Redirect(w ResponseWriter, r *Request, url string, code int):这个函数会让浏览器重定向到 url(可以是基于请求 url 的相对路径),同时指定状态码。

  • http.NotFound(w ResponseWriter, r *Request):这个函数将返回网页没有找到,HTTP 404 错误。

  • http.Error(w ResponseWriter, error string, code int):这个函数返回特定的错误信息和 HTTP 代码。

  • 另一个 http.Request 对象 req 的重要属性:req.Method,这是一个包含 GET 或 POST 字符串,用来描述网页是以何种方式被请求的。

  • w.header().Set("Content-Type", "../..") 设置头信息,比如在网页应用发送 html 字符串的时候,在输出之前执行 w.Header().Set(“Content-Type”, “text/html”),注:w再这里是指http.ResponseWriter

我是demo

package mainimport ("io""net/http"
)const form = `<html><body><form action="#" method="post" name="bar"><input type="text" name="in" /><input type="submit" value="submit"/></form></body></html>
`/* handle a simple get request */
func SimpleServer(w http.ResponseWriter, request *http.Request) {io.WriteString(w, "<h1>hello, world</h1>")
}func FormServer(w http.ResponseWriter, request *http.Request) {w.Header().Set("Content-Type", "text/html")switch request.Method {case "GET":/* display the form to the user */io.WriteString(w, form)case "POST":/* handle the form data, note that ParseForm mustbe called before we can extract form data *///request.ParseForm();//io.WriteString(w, request.Form["in"][0])io.WriteString(w, request.FormValue("in"))}
}func main() {http.HandleFunc("/test1", SimpleServer)http.HandleFunc("/test2", FormServer)if err := http.ListenAndServe(":8088", nil); err != nil {panic(err)}
}
http://www.lryc.cn/news/311345.html

相关文章:

  • FFmpeg+OpenCV开发案例汇总
  • PySide6+VSCode Python可视化环境搭建
  • 【设计】设计一个web版的数据库管理平台后端精要
  • 没有硬件基础可以学单片机吗?
  • ChatGPT引领的AI面试攻略系列:cuda和tensorRT
  • 【战略前沿】人形机器人制造商Figure获得了OpenAI、Jeff Bezos、Nvidia和其他科技巨头的资助
  • 多块磁盘组磁盘离线导致VSAN存储崩溃的VSAN数据恢复案例
  • Jenkins 的安装(详细教程)
  • 使用html网页播放多个视频的几种方法
  • python 基础知识点(蓝桥杯python科目个人复习计划58)
  • 【基于React实现共享单车管理系统】—React基础知识巩固(二)
  • 云桥通+跨境电商:SDWAN企业组网优化跨境网络案例
  • 服务器有几种http强制跳转https设置方法
  • web坦克大战小游戏
  • 如何使用生成式人工智能探索视频博客的魅力?
  • gpt批量工具,gpt批量生成文章工具
  • Python知识汇总
  • WEB面试题
  • Android Studio 六大基本布局详解
  • 如何应对IT服务交付中的问题?
  • [Python] 缓存实用工具
  • php反序列化字符逃逸
  • 延迟加载(Lazy Initialization)的单例模式
  • C++三级专项 流感传染
  • 如何用Elementor创建WordPress会员网站
  • 【脑切片图像分割】MATLAB 图像处理 源码
  • 深度学习系列61:在CPU上运行大模型
  • IO接口 2月5日学习笔记
  • Android Studio开发(一) 构建项目
  • stm32flash模拟eeprom