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)
	}
}
相关推荐
aischang17 分钟前
统信桌面专业版如何使用python开发平台jupyter
开发语言·python·jupyter·统信uos
不像程序员的程序媛32 分钟前
http接口莫名奇妙返回body空白
网络·网络协议·http
狐凄38 分钟前
Python实例题:Python计算概率论
开发语言·python·概率论
q567315231 小时前
分布式增量爬虫实现方案
开发语言·分布式·爬虫·python
勤奋的知更鸟1 小时前
LLaMA-Factory和python版本的兼容性问题解决
开发语言·python·llama-factory
CIb0la1 小时前
Ai自动补全编程工具:llama vscode
运维·开发语言·学习·测试工具·程序人生
1candobetter1 小时前
JAVA后端开发——多租户
java·开发语言
freyazzr2 小时前
C++八股 | Day3 | 智能指针 / 内存管理 / 内存分区 / 内存对齐
开发语言·c++
序属秋秋秋2 小时前
《C++初阶之入门基础》【普通引用 + 常量引用 + 内联函数 + nullptr】
开发语言·c++·笔记
星辰离彬2 小时前
Java 高级泛型实战:8 个场景化编程技巧
java·开发语言·后端·程序人生