本文主要是介绍Go语言入门心法(六): HTTP面向客户端|服务端编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Go语言入门心法(一): 基础语法
Go语言入门心法(二): 结构体
Go语言入门心法(三): 接口
Go语言入门心法(四): 异常体系
Go语言入门心法(五): 函数
Go语言入门心法(六): HTTP面向客户端|服务端编程
Go语言入门心法(七): 并发与通道
Go语言入门心法(八): mysql驱动安装报错onnection failed
Go语言入门心法(九): 引入三方依赖
Go语言入门心法(十):Go语言操作MYSQL(CRUD)|事务处理
Go语言入门心法(十一): 文件处理
Go语言入门心法(十二): GORM映射框架
Go语言入门心法(十三): 反射认知升维
一:go语言面向web编程认知
Go语言的最大优势在于并发与性能,其性能可以媲美C和C++,并发在网络编程中更是至关重要
使用http发送请求,http包提供了HTTP客户端和服务器端的实现,使用HTTP客户端,需要理解和掌握两个非常重要的类型:(1) Client客户端(2) Request求体go语言模拟向浏览器发起HTTP请求,发起请求需要创建一个请求对象,使用NewRequest来创建
package mainimport ("fmt""io""net/http"
)/*
Go语言的最大优势在于并发与性能,其性能可以媲美C和C++,并发在网络编程中更是至关重要
使用http发送请求,http包提供了HTTP客户端和服务器端的实现,使用HTTP客户端,需要理解和掌握两个非常重要的类型:(1) Client客户端(2) Request求体go语言模拟向浏览器发起HTTP请求,发起请求需要创建一个请求对象,使用NewRequest来创建
*/
func main() {// 使用NewRequest模拟浏览器向服务器发送HTTP请求client := &http.Client{}// 访问:爱奇艺-在线视频网站-海量正版高清视频在线观看 首页request, err := http.NewRequest("GET", "https://www.iqiyi.com/", nil)if err != nil {fmt.Println(err)}response, err := client.Do(request)fmt.Println(response.StatusCode)res, err := io.ReadAll(response.Body)if err != nil {fmt.Println(err)}// 打印bodyfmt.Println(string(res))
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerToWebRequest_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerToWebRequest.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerToWebRequest_go.exe
200
<!DOCTYPE html><html data-n-head-ssr><head>
<title>爱奇艺-在线视频网站-海量正版高清视频在线观看</title><meta data-n-head="ssr" charset="utf-8"><meta data-n-head="ssr" name="apple-itunes-app" content="app-id=409563112, app-argument=iqiyi-pad://mobile/home?subtype=iPaihd_0"><meta data-n-head="ssr" name="renderer" content="webkit"><meta data-n-head="ssr" name="bytedance-verification-code" content="OH3/r7XoQqpCuo9kll67"><meta data-n-head="ssr" name="referrer" content="always"><meta data-n-head="ssr" name="google-site-verification" content="X6OJWiV6ws5XxP08OZZNglZpIZD_-EXXeGHyrx7ZTIs"><meta data-n-head="ssr" content="W6H9eWF4xB" data-hid="baidu-site-verification" name="baidu-site-verification"><meta data-n-head="ssr" content="b14bc44b47df0f69871bc8a4b24832df" name="360-site-verification"><meta data-n-head="ssr" content="86697f6b21a3be1fd0dfb363f2103b7b" data-hid="360_ssp_verify" name="360_ssp_verify"><meta data-n-head="ssr" content="text/html; charset=utf-8" http-equiv="Content-Type"><meta data-n-head="ssr" lang="zh-CN" http-equiv="content-language"><meta data-n-head="ssr" content="99E5BCCCE330E1C63C0CC5BDE57AEE80" data-hid="msvalidate.01" name="msvalidate.01"><meta data-n-head="ssr" content="爱奇艺-iQIYI.COM" data-hid="Copyright" name="Copyright"><meta data-n-head="ssr" content="爱奇艺-iQIYI.COM" data-hid="author" name="author"><meta data-n-head="ssr" content="爱奇艺视频-在线视d="title" name="title" lang="zh-CN"><meta data-n-head="ssr" property="og:title" lang="zh-CN" content="爱奇艺视频,视频,视频网站,高清视频,电影,电视剧,动漫,综艺,音乐"><meta data-n-head="ssr" name="description" data-hid="descripti爱奇艺(IQIYI.COM)拥有海量、优质、高清的影视剧集等视频内容。爱奇艺VIP限时新用户特惠:首月6元,会员畅看顶级视听品质体验!当前热播《唐朝诡事录》《一年一度喜剧大赛2》《航海王》《请君》"><meta data-n-head="ssr" itemprop="name" contYI.COM)拥有海量、优质、高清的影视剧集等视频内容。爱奇艺VIP限时新用户特惠:首月6元,会员畅看顶级视听品质体验!当前热播《唐朝诡事录》《一年一度喜剧大赛2》《航海王》《请君》"><meta data-n-head="ssr" name="mobile-agent" content="fol" content="no-transform"><meta data-n-head="ssr" http-equiv="Cache-Control" content="no-siteapp"><meta data-n-head="ssr" itemprop="image" content="//www.iqiyipic.com/pcwimg/128-128-logo.png"><link data-n-head="ssr" rel="icon" type="image/x-icon" href="//www.iqiyipic.com/pcwimg/128-128-logo.png"><link data-n-head="ssr" rel="manifest" href="//www.iqiyi.com/manifest.json"><link data-n-head="ssr" rel="dns-prefetch" href="//cache.video.iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//pcw-api.iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//hm.baidu.com"><link data-n-head="ssr" rel="dns-prefetch" href="//msg.qy.net"><link data-n-head="ssr" rel="dns-prefetch" href="//datax.baidu.com"><link data-n-head="ssr" rel="dns-prefetch" href="//static.iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//static-s.iqiyi.com"><link data-n-head="ssr" rel="alternate" hreflang="zh-CN" href="//www.iqiyi.com/"><link data-n-head="ssr" rel="alternate" hreflang="zh-TW" href="//tw.iqiyi.com/"><link data-n-head="ssr" rel="alternate" hreflang="zh" href="//www.iqiyi.com/"><link data-n-head="ssr" rel="apple-to
uch-icon-precomposed" size="114x114" href="//www.iqiyipic.com/pcwimg/PCW-114x114.png"><link data-n-head="ssr" rel="apple-touch-icon-precomposed" size="72x72" href="//www.iqiyipic.com/pcwimg/PCW-72X72.png"><link
data-n-head="ssr" rel="canonical" href="//www.iqiyi.com/"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/cb0d597.js" as="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/app.069a04f.css" as="style">
<link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/app.40d67a8dd3deb57c860f.js" as="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/pages/index.0a766132af6dafcff12c.js" as="script"><link rel="preload"
href="//stc.iqiyipic.com/gaze/pcw/ssr/pages/cloudCinema/pages/cloudCinema1/pages/cloudCinemaPCA/pages/cloudCinemaPCA1/pages/components/pag/8c7f18db.462771861c0e477fb66d.js" as="script"><link rel="preload" href="//stc.iqiyipic.
com/gaze/pcw/ssr/pages/cloudCinema1/pages/cloudCinemaPCA1/pages/dianshiju/index/pages/dianying/pages/dongman/pages/in/2acb21ce.bde7a64cfc3a00b86ccd.js" as="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/page
s/index/home2020.fa65e0e453b40bc444aa.js" as="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/36.26673fa.css" as="style"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/36.9330c2e3eccd15b6ff28.js" a
s="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/122.837a6dc01d4662378290.js" as="script"><link rel="preload" href="//stc.iqiyipic.com/gaze/pcw/ssr/common.1522f29.css" as="style"><link rel="preload" href="/
/stc.iqiyipic.com/gaze/pcw/ssr/common.645cc65cefcb24b2a483.js" as="script"><link rel="stylesheet" href="//stc.iqiyipic.com/gaze/pcw/ssr/app.069a04f.css"><link rel="stylesheet" href="//stc.iqiyipic.com/gaze/pcw/ssr/36.26673fa.css"><link rel="stylesheet" href="//stc.iqiyipic.com/gaze/pcw/ssr/common.1522f29.css">
<script>window.qyTtiStart = Date.now()</script></head>
<body>
<div data-server-rendered="true" id="__nuxt"><!----><div id="__layout"><div data-v-5f1d06ee><div id="adSkinInner" class="qy-dark" data-v-5f1d06ee><div id="I71Layout"></div> <div style="display:none">10/16/2023, 8:03:36 PM<
/div> <!----> <div data-v-5f1d06ee><div class="skin_focus"></div> <div id="1000000000714" style="display: none;"><a id="adClick" οnfοcus="this.blur();" style="width: 100%; position: absolute;"></a> <div id="adDiv" style="width
: 970px; margin: 0px auto -25px;"></div></div></div> <div class="ph-skin-wrap"><header id="block-A" data-block-v2="712211_topNav" class="qy-header home2020 r-type1 greendark qy-header--bg qy-header--absolute"><div class="heade
r-wrap"><div class="header-inner"><div class="qy-logo"><a href="//www.iqiyi.com/" title="爱奇艺视频" data-rseat-v2="iQIYI_logo" class="logo-link2"></a></div><!----><div class="qy-header-side"><!----><div class="header__search"
><div class="client-only-placeholder"><div class="search-box"><span class="search-box-in"><input autocomplete="off" type="text" data-rseat-v2="712211_search_input" class="search-box-input"></span><span class="search-box-out"><
span type="button" class="search-box-btn"><i class="qy20-header-svg qy20-header-svg-search"></i></span></span></div></div></div><div class="header-sideItem header-vip"><div class="client-only-placeholder"><div class="header-si
deItemCon header-vip-login"><i class="header-sideItemIcon qy20-header-svg qy20-header-svg-vip"></i><span class="header__item__tit">VIP</span></div></div></div><div class="header-sideItem qy-header__game"><div class="client-onl
y-placeholder"><a href="//pc.game.iqiyi.com?startfrom=pcw_topbanner " target="_blank" data-rseat-v2="tj_gamecenter" class="header-sideItemCon"><i class="header-sideItemIcon qy20-header-svg qy20-header-svg-game"></i><span class
="header__item__tit">游戏</span></a></div></div><div class="header-sideItem header-upload"><div class="client-only-placeholder"><span data-rseat-v2="712211_upload_ugc" class="header-sideItemCon"><i class="header-sideItemIcon q
y20-header-svg qy20-header-svg-upload"></i><span id="nav_uploadHref" class="header__item__tit">上传</span></span></div></div><div class="header-sideItem header-download"><div class="client-only-placeholder"><div class="header-
sideItemCon"><i class="header-sideItemIcon qy20-header-svg qy20-header-svg-pca-dwn"></i><span class="header__item__tit">客户端</span></div></div></div><div class="header-sideItem header-record"><div class="client-only-placehol
der"><a target="_blank" rel="nofollow" href="//www.iqiyi.com/u/record" data-rseat-v2="tj_history" class="header-sideItemCon"><i class="header-sideItemIcon qy20-header-svg qy20-header-svg-record"></i><span class="header__item__tit">看过</span></a></div></div><div class="header-sideItem header-user"><div class="client-only-placeholder"><div class="header-sideItemCon"><a rel="nofollow" class="header-userLink"><img id="J-user-img" src="
//www.iqiyipic.com/common/fix/site-v5/header-userImg-default-dark.png>..............................................................................................................................................................
二: 添加请求体Cookie,伪装浏览器登录状态
模拟流量器登录:
当访问某些资源时,需要登录后才能访问,此时我们模拟登录,使得被访问的资源知道我们使用go编程的爬虫客户端是登录状态;
这就需要设置Cookie,Cookie通常用来标识客户端的登录状态;Request实例可以使用AddCookie方法给请求添加Cookie
package mainimport ("fmt""io""net/http""strconv"
)/*
模拟流量器登录:
当访问某些资源时,需要登录后才能访问,此时我们模拟登录,使得被访问的资源知道我们使用go编程的爬虫客户端是登录状态;
这就需要设置Cookie,Cookie通常用来标识客户端的登录状态;Request实例可以使用AddCookie方法给请求添加Cookie
*/
func main() {client := &http.Client{}request, err := http.NewRequest("GET", "https://www.iqiyi.com/", nil)if err != nil {fmt.Println(err)}// 使用http.Cookie结构体初始化一个Cookie键值对cookie := &http.Cookie{Name: "userId", Value: strconv.Itoa(12345)}// 使用前面的构建的request方法AddCookie往请求中添加Cookierequest.AddCookie(cookie)request.AddCookie(&http.Cookie{Name: "session", Value: "YWRtaW4="})response, err := client.Do(request)fmt.Println(response.Request.Cookies())fmt.Println(response.StatusCode)res, err := io.ReadAll(response.Body)if err != nil {fmt.Println(err)}// 打印bodyfmt.Println(string(res))
}
运行效果: 通常服务器使用session来判断客户端是否为登录用户
[userId=12345 session=YWRtaW4=]
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerToCookieLoginBrowser_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerToCookieLoginBrowser.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerToCookieLoginBrowser_go.exe
[userId=12345 session=YWRtaW4=]
200
<!DOCTYPE html><html data-n-head-ssr><head>
<title>爱奇艺-在线视频网站-海量正版高清视频在线观看</title><meta data-n-head="ssr" charset="utf-8"><meta data-n-head="ssr" name="apple-itunes-app" content="app-id=409563112, app-argument=iqiyi-pad://mobile/home?subtype=iPaihd_0"><meta data-n-head="ssr" name="renderer" content="webkit"><meta data-n-head="ssr" name="bytedance-verification-code" content="OH3/r7XoQqpCuo9kll67"><meta data-n-head="ssr" name="referrer" content="always"><meta data-n-head="ssr" name="google-site-verification" content="X6OJWiV6ws5XxP08OZZNglZpIZD_-EXXeGHyrx7ZTIs"><meta data-n-head="ssr" content="W6H9eWF4xB" data-hid="baidu-site-verification" name="baidu-site-verification"><meta data-n-head="ssr" content="b14bc44b47df0f69871bc8a4b24832df" name="360-site-verification"><meta data-n-head="ssr" content="86697f6b21a3be1fd0dfb363f2103b7b" data-hid="360_ssp_verify" name="360_ssp_verify"><meta data-n-head="ssr" content="text/html; charset=utf-8" http-equiv="Content-Type"><meta data-n-head="ssr" lang="zh-CN" http-equiv="content-language"><meta data-n-head="ssr" content="99E5BCCCE330E1C63C0CC5BDE57AEE80" data-hid="msvalidate.01" name="msvalidate.01"><meta data-n-head="ssr" content="爱奇艺-iQIYI.COM" data-hid="Copyright" name="Copyright"><meta data-n-head="ssr" content="爱奇艺-iQIYI.COM" data-hid="author" name="author"><meta data-n-head="ssr" content="爱奇艺视频-在线视d="title" name="title" lang="zh-CN"><meta data-n-head="ssr" property="og:title" lang="zh-CN" content="爱奇艺视频,视频,视频网站,高清视频,电影,电视剧,动漫,综艺,音乐"><meta data-n-head="ssr" name="description" data-hid="descripti爱奇艺(IQIYI.COM)拥有海量、优质、高清的影视剧集等视频内容。爱奇艺VIP限时新用户特惠:首月6元,会员畅看顶级视听品质体验!当前热播《唐朝诡事录》《一年一度喜剧大赛2》《航海王》《请君》"><meta data-n-head="ssr" itemprop="name" cont
YI.COM)拥有海量、优质、高清的影视剧集等视频内容。爱奇艺VIP限时新 新
户特惠:首月6元,会员畅看顶级视听品质体验!当前热播《唐朝诡事录》《一年一度喜剧大赛2》《航海王》《请君》"><meta data-n-head="ssr" name="mobile-agent" content="format=html5;url=//m.iqiyi.com/"><meta data-n-head="ssr" http-equ u
iv="Cache-Control" content="no-transform"><meta data-n-head="ssr" http-equiv="Cache-Control" content="no-siteapp"><meta data-n-head="ssr" itemprop="image" content="//www.iqiyipic.com/pcwimg/128-128-logo.png"><link data-n-head=
"ssr" rel="icon" type="image/x-icon" href="//www.iqiyipic.com/pcwimg/128-128-logo.png"><link data-n-head="ssr" rel="manifest" href="//www.iqiyi.com/manifest.json"><link data-n-head="ssr" rel="dns-prefetch" href="//cache.video.
iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//pcw-api.iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//hm.baidu.com"><link data-n-head="ssr" rel="dns-prefetch" href="//msg.qy.net"><link data-n-head
="ssr" rel="dns-prefetch" href="//datax.baidu.com"><link data-n-head="ssr" rel="dns-prefetch" href="//static.iqiyi.com"><link data-n-head="ssr" rel="dns-prefetch" href="//static-s.iqiyi.com"><link data-n-head="ssr" rel="altern
ate" hreflang="zh-CN" href="//www.iqiyi.com/">
三: 请求体添加Header,绕过反爬策略
有需网站作了反爬措施,一般会通过根据Header头中的User-Agent的值解析判断是浏览器还是爬虫;
这时我们需要设置成浏览器的UA来绕过这类反爬措施;Request可以直接使用request.Header.Set(key,value)来设置Header
package mainimport ("compress/flate""compress/gzip""fmt""io""net/http"
)func main() {println(`有需网站作了反爬措施,一般会通过根据Header头中的User-Agent的值解析判断是浏览器还是爬虫;这时我们需要设置成浏览器的UA来绕过这类反爬措施;Request可以直接使用request.Header.Set(key,value)来设置Header`)client := &http.Client{}request, err := http.NewRequest("GET", "http://www.baidu.com/", nil)if err != nil {fmt.Println(err)}// 设置request的header,具体可参考HTTP协议request.Header.Set("Accept", "text/html, application/xhtml+xml, application/xml;q=0.9,*/*;q=0.8")request.Header.Set("Accept-Charset", "UTF-8, utf-8;q=0.7, *; q=0.3")request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")request.Header.Set("Cache-Control", "max-age=0")request.Header.Set("Connection", "keep-alive")request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0;WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/72.0.3626.121 Safari/537.36")response, err := client.Do(request)fmt.Printf("%#v", response.Request.Header)//res, err := io.ReadAll(response.Body)switch response.Header.Get("Content-Encoding") {case "gzip":bodyReader, err := gzip.NewReader(response.Body)if err != nil {fmt.Println(err)}res, err := io.ReadAll(bodyReader)// 打印bodyfmt.Println(string(res))case "deflate":bodyReader := flate.NewReader(response.Body)res, err := io.ReadAll(bodyReader)if err != nil {fmt.Println(err)}// 打印bodyfmt.Println(string(res))default:bodyReader := response.Bodyres, err := io.ReadAll(bodyReader)if err != nil {fmt.Println(err)}// 打印bodyfmt.Println(string(res))}
}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerGetToSetHeaderRequest_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerGetToSetHeaderRequest.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerGetToSetHeaderRequest_go.exe有需网站作了反爬措施,一般会通过根据Header头中的User-Agent的值解析判断是浏览器还是爬虫;
这时我们需要设置成浏览器的UA来绕过这类反爬措施;Request可以直接使用request.Header.Set(key,value)来设置Headerhttp.Header{"Accept":[]string{"text/html, application/xhtml+xml, application/xml;q=0.9,*/*;q=0.8"}, "Accept-Charset":[]string{"UTF-8, utf-8;q=0.7, *; q=0.3"}, "Accept-Encoding":[]string{"gzip,deflate,sdch"}, "Accept-Language":[]string{"zh-CN,zh;q=0.8"}, "Cache-Control":[]string{"max-age=0"}, "Connection":[]string{"keep-alive"}, "Referer":[]string{"http://www.baidu.com/"}, "User-Agent":[]string{"Mozilla/5.0 (Windows NT 10.0;WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/72.0.3626.121 Safari/537.36"}}
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#ffffff"><meta name="description" content="全球领先的中文搜索引擎、致力于让网民更便捷地获取信息,找到所求。百度超过千亿的中文网页数据库,可以瞬间找到相aidu.com/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" /><link rel="icon" sizes="any" mask href="https://www.baidu.com/favicon.iclink rel="dns-prefetch" href="//dss0.bdstatic.com"/><link rel="dns-prefetch" href="//dss1.bdstatic.com"/><link rel="dns-prefetch" href="//ss1.bdstatic.com"/><link rel="dns-prefetch" href="//sp0.baidu.com"/><link rel="dns-prefetch" href="//sp1.baidu.com"/><link rel="dns-prefetch" href="//sp2.baidu.com"/><link rel="dns-prefetch" href="//pss.bdstatic.com"/><link rel="apple-touch-icon-precomposed" href="https://psstatic.cdn.bcebos.com/video/wiseindex/aa6eef91f8b5b1a33b454c401_1660835115000.png"><title>百度一下,你就知道</title>
四: 直接使用Get(url)函数发送请求
Client类型包含get方法,get方法时对Do方法的封装,使用get方法可以快速发起一个get请求;
http包中也有一个叫GET的方法,底层就是调用Client的GET方法
package mainimport ("fmt""io/ioutil""net/http"
)/*
Client类型包含get方法,get方法时对Do方法的封装,使用get方法可以快速发起一个get请求;
http包中也有一个叫GET的方法,底层就是调用Client的GET方法
*/
func main() {// http.Get实际上是DefaultClient.Get(url),Get函数是高度封装的,只有一个参数Url// 对于一般的http Request是可以使用,但是不能定制Requestresponse, err := http.Get("http://www.baidu.com")if err != nil {fmt.Println(err)}defer response.Body.Close()body, _ := ioutil.ReadAll(response.Body)fmt.Println(string(body))}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerUseGetMethodToSendRequest_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerUseGetMethodToSendRequest.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerUseGetMethodToSendRequest_go.exe
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#ffffff"><meta name="description" content="全球领先的中文搜索引擎、致力于让网民更便捷地获取信息,找到所求。百度超过千亿的中文网页数据库,可以瞬间找到相关的搜索结果。"><link rel="shortcut icon" href="https://warch" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" /><link rel="icon" sizes="any" mask href="https://www.baidu.com/favicon.ico"><link rel="dns-prefetch" href="//dss0.bdstatic.com"/>< rel="dns-prefetch" href="//dss1.bdstatic.com"/><link rel="dns-prefetch" href="//ss1.bdstatic.com"/><link rel="dns-prefetch" href="//sp0.baidu.com"/><link rel="dns-prefetch" href="//sp1.baidu.com"/><link rel="dns-prefetch" href="//sp2.baidu.com"/>
五: Post()携带数据发送请求
post发送web请求Post向指定的URL发送一个post请求,bodyType为post数据的类型,body为post数据,作为请求主体。如果参数body实现了io.Close接口,它会在请求后被关闭,调用者有责任读取完返回值resp的主体后关闭它,该方法时对Client的POST方法的封装
package mainimport ("fmt""io/ioutil""net/http""strings"
)/*
post发送web请求Post向指定的URL发送一个post请求,bodyType为post数据的类型,body为post数据,作为请求主体。如果参数body实现了io.Close接口,它会在请求后被关闭,调用者有责任读取完返回值resp的主体后关闭它,该方法时对Client的POST方法的封装
*/
func main() {resp, err := http.Post("https://blog.csdn.net/u014396256/article/details/84645350","application/x-www-form-urlencoded",strings.NewReader("user=admin&pass=admin"))if err != nil {fmt.Println(err)}defer resp.Body.Close()body, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Println(err)}fmt.Println(string(body))}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerPostToWebRequest_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerPostToWebRequest.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerPostToWebRequest_go.exe
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<link rel="canonical" href="https://blog.csdn.net/u014396256/article/details/84645350"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="renderer" content="webkit"/>
<meta name="force-rendering" content="webkit"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="report" content='{"spm":"1001.2101","extra":{"titAb":"t_1","lvab":"t_1"},"pid":"blog"}'>
<meta name="referrer" content="always">
<meta http-equiv="Cache-Control" content="no-siteapp" /><link rel="alternate" media="handheld" href="#" />
<meta name="shenma-site-verification" content="5a59773ab8077d4a62bf469ab966a63b_1497598848">
<meta name="applicable-device" content="pc">
<link href="https://g.csdnimg.cn/static/logo/favicon32.ico" rel="shortcut icon" type="image/x-icon" />
<title>解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客</title>
<script>
(function(){
var el = document.createElement("script");
el.src = "https://s3a.pstatp.com/toutiao/push.js?1abfa13dfe74d72d41d83c86d240de427e7cac50c51ead53b2e79d40c7952a23ed7716d05b4a0f683a653eab3e214672511de2457e74e99286eb2c33f4428830";
el.id = "ttzz";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(el, s);
})(window)
</script>
<meta name="keywords" content="responsebody返回中文乱码">
<meta name="csdn-baidu-search" content='{"autorun":true,"install":true,"keyword":"responsebody返回中文乱码"}'>
<meta name="description" content="用@ResponseBody注解返回字符串时,发现返回页面上的中文是乱码,这个问题 是由于 spring mvc 使用了StringHttpMessageConverter ;来看一下这个类public class StringHttpMessageConverter extends AbstractHttpMessageConverter&lt;String&gt; { publ..._responsebody返回中文乱码">
{"@context":"https://ziyuan.baidu.com/contexts/cambrian.jsonld","@id":"https://blog.csdn.net/u014396256/article/details/84645350","appid":"1638831770136827","pubDate":"2018-11-30T11:02:20","title":"解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客","upDate":"2018-11-30T11:02:20"}</script>
<link rel="stylesheet" type="text/css" href="https://csdnimg.cn/release/blogv2/dist/pc/themesSkin/skin-yellow/skin-yellow-28d34ab5fa.min.css">
<script src="https://csdnimg.cn/public/common/libs/jquery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var isCorporate = false;//注释删除enterprise
var articleTitle = "解决@ResponseBody注解返回中文乱码";
var articleDesc = "用@ResponseBody注解返回字符串时,发现返回页面上的中文是乱码,这个问题 是由于 spring mvc 使用了StringHttpMessageConverter ;来看一下这个类public class StringHttpMessageConverter extends AbstractHttpMessageConverter&lt;String&gt; { publ..._responsebody返回中文乱码";
var articleTitles = "解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客";
var nickName = "栋栋哥哥";
var articleDetailUrl = "https://blog.csdn.net/u014396256/article/details/84645350";
if(window.location.host.split('.').length == 3) {
blog_address = blogUrl + username;
<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/pc/css/blog_code-01256533b5.min.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/chart-3456820cac.css" />
六: PostForm()携带数据发送请求
除了Post携带参数发送请求外,还可以使用PostForm(url string,data url.Values)函数封装请求数据,向服务器发送请求;
该方法是对Client的PostForm方法的包装
package mainimport ("fmt""io/ioutil""net/http""net/url"
)/*
除了Post携带参数发送请求外,还可以使用PostForm(url string,data url.Values)函数封装请求数据,向服务器发送请求;
该方法是对Client的PostForm方法的包装
*/
func main() {resp, err := http.PostForm("https://blog.csdn.net/u014396256/article/details/84645350",url.Values{"user": {"admin"}, "password": {"admin"}})if err != nil {fmt.Println(err)}defer resp.Body.Close()readBytes, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Println(err)}fmt.Println(string(readBytes))}
运行效果:
GOROOT=D:\program_file_worker\go1.20 #gosetup
GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerPostFormToWebRequest_go.exe D:\program_file\go_workspace\org.jd.data\http\OOPHttpServerPostFormToWebRequest.go #gosetup
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPHttpServerPostFormToWebRequest_go.exe
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<link rel="canonical" href="https://blog.csdn.net/u014396256/article/details/84645350"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="renderer" content="webkit"/>
<meta name="force-rendering" content="webkit"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="report" content='{"spm":"1001.2101","extra":{"titAb":"t_1","lvab":"t_1"},"pid":"blog"}'>
<meta name="referrer" content="always">
<meta http-equiv="Cache-Control" content="no-siteapp" /><link rel="alternate" media="handheld" href="#" />
<meta name="shenma-site-verification" content="5a59773ab8077d4a62bf469ab966a63b_1497598848">
<meta name="applicable-device" content="pc">
<link href="https://g.csdnimg.cn/static/logo/favicon32.ico" rel="shortcut icon" type="image/x-icon" />
<title>解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客</title>
<script>
(function(){
var el = document.createElement("script");
el.src = "https://s3a.pstatp.com/toutiao/push.js?1abfa13dfe74d72d41d83c86d240de427e7cac50c51ead53b2e79d40c7952a23ed7716d05b4a0f683a653eab3e214672511de2457e74e99286eb2c33f4428830";
el.id = "ttzz";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(el, s);
})(window)
</script>
<meta name="keywords" content="responsebody返回中文乱码">
<meta name="csdn-baidu-search" content='{"autorun":true,"install":true,"keyword":"responsebody返回中文乱码"}'>
<meta name="description" content="用@ResponseBody注解返回字符串时,发现返回页面上的中文是乱码,这个问题 是由于 spring mvc 使用了StringHttpMessageConverter ;来看一下这个类public class StringHttpMessageConverter extends AbstractHttpMessageConverter&lt;String&gt; { publ..._responsebody返回中文乱码">
<link rel="stylesheet" type="text/css" href="https://csdnimg.cn/release/blogv2/dist/pc/css/detail_enter-3ed6edfc90.min.css">
<style>
{"@context":"https://ziyuan.baidu.com/contexts/cambrian.jsonld","@id":"https://blog.csdn.net/u014396256/article/details/84645350","appid":"1638831770136827","pubDate":"2018-11-30T11:02:20","title":"解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客","upDate":"2018-11-30T11:02:20"}</script>
<link rel="stylesheet" type="text/css" href="https://csdnimg.cn/release/blogv2/dist/pc/themesSkin/skin-yellow/skin-yellow-28d34ab5fa.min.css">
<script src="https://csdnimg.cn/public/common/libs/jquery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var isCorporate = false;//注释删除enterprise
var username = "u014396256";
var skinImg = "white";
var blog_address = "https://blog.csdn.net/u014396256";
var currentUserName = "";
var isOwner = false;
var loginUrl = "http://passport.csdn.net/account/login?from=https://blog.csdn.net/u014396256/article/details/84645350";
var blogUrl = "https://blog.csdn.net/";
var avatar = "https://profile-avatar.csdnimg.cn/cf1b806fc8104885bf468699791fde76_u014396256.jpg!1";
var articleTitle = "解决@ResponseBody注解返回中文乱码";
var articleDesc = "用@ResponseBody注解返回字符串时,发现返回页面上的中文是乱码,这个问题 是由于 spring mvc 使用了StringHttpMessageConverter ;来看一下这个类public class StringHttpMessageConverter extends AbstractHttpMessageConverter&lt;String&gt; { publ..._responsebody返回中文乱码";
var articleTitles = "解决@ResponseBody注解返回中文乱码_responsebody返回中文乱码-CSDN博客";
var nickName = "栋栋哥哥";
var articleDetailUrl = "https://blog.csdn.net/u014396256/article/details/84645350";
if(window.location.host.split('.').length == 3) {
blog_address = blogUrl + username;
}
</head>
<body class="nodata " style="">
<div id="toolbarBox" style="min-height: 48px;"></div>
<script>
var toolbarSearchExt = '{"landingWord":["responsebody返回中文乱码"],"queryWord":"","tag":[],"title":"解决@ResponseBody注解返回中文乱码"}';
</script>
<script src="https://g.csdnimg.cn/common/csdn-toolbar/csdn-toolbar.js" type="text/javascript"></script>
七: 启动HTTP服务器
package mainimport ("fmt""log""net/http"
)/*
go语言http服务器端处理器认知:启动HTTP服务器
*/
func main() {http.HandleFunc("/findData", firstHttpServerHandler)err := http.ListenAndServe(":8080", nil)if err != nil {log.Fatal("ListenAndServer: ", err)}println("服务已经启动,正在监听8080端口..........")
}func firstHttpServerHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "你好,这是go语言面向web服务器编程的第一个后端处理器")
}
启动该服务,会监听8080端口......在浏览器中访问: http://localhost:8080/findData
在浏览器中访问: http://localhost:8080/findData
服务端返回响应内容: 你好,这是go语言面向web服务器编程的第一个后端处理器
八: 启动HTTPS服务器
package mainimport ("fmt""log""net/http""time"
)/*
启动HTTPS服务器:http包提供了http.ListenAndServeTLS函数来启动一个HTTPS服务器端,ListenAndServeTLS函数和ListenAndServe函数基本一致;除了它期望的是HTTPS连接之外;此外还必须提供必要的证书文件和密钥文件;
*/
func main() {http.HandleFunc("/getData", firstHttpsServerHandler)err := http.ListenAndServeTLS(":8443", "D:/program_file/go_workspace/org.jd.data/http/file/server.csr","D:/program_file/go_workspace/org.jd.data/http/file/server.csr", nil)if err != nil {log.Fatal("系统异常: ", err)}println("服务器启动成功")
}func firstHttpsServerHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "欢迎来到Go语言编写的第一个https服务端!,你于 %s 访问了服务器端", time.Now().Format("15:02:02"))
}
curl --insecure https://127.0.0.1:8443/getData
欢迎来到Go语言编写的第一个https服务端!,你于 10:30:20 访问了服务器端
九: 搭建文件资源服务器
package mainimport ("fmt""log""net/http""time"
)/*
静态服务器资源:
*/
func main() {http.HandleFunc("/findFile", indexFile)// 设置静态目录fsh := http.FileServer(http.Dir("D:/program_file/go_workspace/org.jd.data/http/static"))http.Handle("/static/", http.StripPrefix("/static/", fsh))err := http.ListenAndServe(":8080", nil)if err != nil {log.Fatal("ListenAndServer: ", err)}println("服务已经启动,正在监听8080端口..........")
}func indexFile(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "你好,这是go语言面向web服务器编程的第一个后端处理器: %s", time.Now().Format("15:04:05"))
}
运行效果:启动服务器
服务文件资源: http://127.0.0.1:8080/static/
访问动态服务接口数据:
http://127.0.0.1:8080/findFile
十: 路由提供多个访问服务
服务器端路由认知:
默认的http包中的mux不支持带参数的路由,根据经验,只要你的路由带有参数,并且这个项目的API数目超过了10个,就尽量不要使用net/http中默认
的路由。在Go开源界应用最广泛的router是httpRouter,很多开源框架都是基于HttpRouter进行一定程度的改造的成果;
比如gin框架。
package mainimport ("fmt""log""net/http""time"
)/*
服务器端路由认知:默认的http包中的mux不支持带参数的路由,根据经验,只要你的路由带有参数,并且这个项目的API数目超过了10个,就尽量不要使用net/http中默认的路由。在Go开源界应用最广泛的router是httpRouter,很多开源框架都是基于HttpRouter进行一定程度的改造的成果;比如gin框架。
*/
func main() {// 创建一个路由转发器mux := http.NewServeMux()// 给hello函数注册timeHandler中间件mux.Handle("/findHello", timeHandler(http.HandlerFunc(helloHandler)))mux.Handle("/findIndex", timeHandler(http.HandlerFunc(indexHandler)))http.ListenAndServe(":8080", mux)
}func timeHandler(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {start := time.Now()log.Printf("Started %s %s\n", r.Method, r.URL.Path)next.ServeHTTP(w, r)log.Printf("Completed %s in %v\n", r.URL.Path, time.Since(start))})
}
func indexHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "This is index")
}func helloHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "hello world !")
}
运行效果:
十一: Web框架Gin认知升维
先将gin安装一下,安装依赖go语言还是比较方便的。
在安装之前先配置一下goproxy。
go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/ //阿里代理
go env -w GOPROXY=https://goproxy.cn //七牛云代理
本地下载:Gin框架
PS D:\program_file\go_workspace> go get -u github.com/gin-gonic/gin
go: downloading github.com/gin-gonic/gin v1.9.1
go: downloading golang.org/x/net v0.10.0
go: downloading github.com/gin-contrib/sse v0.1.0
go: downloading github.com/mattn/go-isatty v0.0.19
go: downloading github.com/go-playground/validator/v10 v10.14.0
go: downloading github.com/pelletier/go-toml/v2 v2.0.8
go: downloading github.com/ugorji/go/codec v1.2.11
go: downloading google.golang.org/protobuf v1.30.0
go: downloading gopkg.in/yaml.v3 v3.0.1
go: downloading github.com/bytedance/sonic v1.9.1
go: downloading github.com/goccy/go-json v0.10.2
go: downloading github.com/json-iterator/go v1.1.12
11.1 使用gin框架启动http服务器
使用Gin框架启动一个Http服务器比较简单,使用gin.Default()初始化一个gin.Engine对象,后面所有的操作都是基于这个对象,如添加路由解析.
package mainimport ("github.com/gin-gonic/gin""net/http"
)func main() {route := gin.Default()route.GET("/ping", func(context *gin.Context) {context.JSON(http.StatusOK, gin.H{"name": "张三","age": 30,"message": "ping",})})route.Run(":8080") // listen and serve on 0.0.0.0:8080
}
运行效果:
11.2 使用gin框架搭建静态资源服务器
package mainimport ("github.com/gin-gonic/gin""net/http" )func main() {router := gin.Default()// 静态资源加载,本实例为css,js以及资源图片router.StaticFS("/static", http.Dir("D:/program_file/go_workspace/org.jd.data/http/static"))router.StaticFile("favicon.ico", "./static/favicon.ico")// listen and server on 0.0.0.8080router.Run(":8080") }
十二: Web路由框架Gin获取URL中携带参数
携带参数的路由认知使用gin框架的最大好处就是它的路由非常的方便,并且支持较为复杂的路由,下面对URL地址中携带参数的路由进行实践;URL路由携带参数有两种情况:(1)一种是arg,主要传递参数值如name(2)另一种是*arg,主要传递路径/user/:name/*action这两种方式都可以使用c.Param方法去除数据c.Param("name") // 如"zhangSan"c.Param("action ") // 如"/send"
package main/*
携带参数的路由认知使用gin框架的最大好处就是它的路由非常的方便,并且支持较为复杂的路由,下面对URL地址中携带参数的路由进行实践;URL路由携带参数有两种情况:(1)一种是arg,主要传递参数值如name(2)另一种是*arg,主要传递路径/user/:name/*action这两种方式都可以使用c.Param方法去除数据c.Param("name") // 如"zhangSan"c.Param("action ") // 如"/send"
*/
import ("github.com/gin-gonic/gin""net/http"
)func main() {router := gin.Default()router.GET("/user/:name", func(context *gin.Context) {// 获取URL中携带的参数name的值name := context.Param("name")context.String(http.StatusOK, "Hello, %s 欢迎来到Gin框架Router版块!想深入学习请参考官方网站:\n"+"https://gin-gonic.com/zh-cn/docs/examples/using-basicauth-middleware/ ", name)})router.GET("/user/:name/*action", func(context *gin.Context) {// 获取URL中携带的参数name的值name := context.Param("name")action := context.Param("action")message := context.Request.Method + " => " + name + " is " + actioncontext.String(http.StatusOK, message)})router.POST("/user/:name/*action", func(context *gin.Context) {name := context.Param("name")action := context.Param("action")message := context.Request.Method + " => " + name + " is " + actioncontext.String(http.StatusOK, message)})router.Run(":8080")
}
运行效果:
这篇关于Go语言入门心法(六): HTTP面向客户端|服务端编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!