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

下午就不能好好学习一下golang,业务一直找个不停,自己定的业务规则都能忘得一干二净,让你查半天,完全是浪费时间。
golang实现访问并读取页面数据

go 复制代码
package main

import (
	"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

go 复制代码
package main

import (
	"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 包将这个状态解析成为一个结构

go 复制代码
package main

import (
	"encoding/xml"
	"fmt"
	"net/http"
)

/*这个结构会保存解析后的返回数据。
他们会形成有层级的 XML,可以忽略一些无用的数据*/
type Status struct {
	Text string
}

type User struct {
	XMLName xml.Name
	Status  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

go 复制代码
package main

import (
	"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 must
		   be 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)
	}
}
相关推荐
moonless022218 小时前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty2 天前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序