package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
testHttpNewRequest()
}
func testHttpNewRequest() {
// 1.創(chuàng)建一個(gè)客戶端
client := http.Client{}
// 2.創(chuàng)建一個(gè)請(qǐng)求雳灾,請(qǐng)求方式既可以是GET, 也可以是POST
request, err := http.NewRequest("GET", "https://www.toutiao.com/search/suggest/initial_page/", nil)
checkErr(err)
// 3.客戶端發(fā)送請(qǐng)求
cookName := &http.Cookie{Name:"username", Value: "Steven"}
// 添加cookie
request.AddCookie(cookName)
// 設(shè)置請(qǐng)求頭
request.Header.Set("Accept-Language", "zh-cn")
fmt.Printf("Header:%v \n", request.Header)
response, err := client.Do(request)
checkErr(err)
defer response.Body.Close()
// 查看請(qǐng)求頭的數(shù)據(jù)
fmt.Printf("相應(yīng)狀態(tài)碼:%v \n", response.StatusCode)
// 4.操作數(shù)據(jù)
if response.StatusCode == 200 {
data, err := ioutil.ReadAll(response.Body)
fmt.Println("網(wǎng)絡(luò)請(qǐng)求成功")
checkErr(err)
fmt.Println(string(data))
} else {
fmt.Println("網(wǎng)絡(luò)請(qǐng)求失敗", response.Status)
}
}
func checkErr(err error) {
fmt.Println("09-----------")
defer func() {
if ins,ok := recover().(error);ok { // 這種recover的使用方式
fmt.Println("程序出現(xiàn)異常:", ins.Error())
}
}()
if err != nil {
panic(err)
}
}
package main
import (
"fmt"
"net/http"
)
func main() {
testClientGet()
}
func testClientGet() {
// 創(chuàng)建客戶端
client := http.Client{}
// 通過client去請(qǐng)求
response, err := client.Get("https://www.toutiao.com/search/suggest/initial_page/")
checkErr(err)
fmt.Printf("響應(yīng)狀態(tài)碼:%v \n", response.StatusCode)
if response.StatusCode == 200 {
fmt.Println("網(wǎng)絡(luò)請(qǐng)求成功")
defer response.Body.Close()
}
}
func checkErr(err error) {
fmt.Println("09-----------")
defer func() {
if ins,ok := recover().(error);ok { // 這種recover的使用方式
fmt.Println("程序出現(xiàn)異常:", ins.Error())
}
}()
if err != nil {
panic(err)
}
}
- 使用client. Post()或client.PostForm()方法
- 使用http. Get()方法
package main
import (
"fmt"
"net/http"
)
func main() {
testHttpGet()
}
func testHttpGet() {
response, err := http.Get("http://www.baidu.com")
checkErr(err)
fmt.Printf("響應(yīng)狀態(tài)碼:%v \n", response.StatusCode)
if response.StatusCode == 200 {
fmt.Println("網(wǎng)絡(luò)請(qǐng)求成功")
defer response.Body.Close()
} else {
fmt.Println("請(qǐng)求失敗",response.Status)
}
}
func checkErr(err error) {
fmt.Println("09-----------")
defer func() {
if ins,ok := recover().(error);ok { // 這種recover的使用方式
fmt.Println("程序出現(xiàn)異常:", ins.Error())
}
}()
if err != nil {
panic(err)
}
}
- 使用http. Post()或http.PostForm()方法
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
testHttpPost()
}
func testHttpPost() {
//構(gòu)建參數(shù)
data := url.Values{
"theCityName" : {"重慶"},
}
// 參數(shù)轉(zhuǎn)化為body
reader := strings.NewReader(data.Encode())
fmt.Println(reader)
// 發(fā)起post請(qǐng)求,MIME 格式
response, err := http.Post("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName",
"application/x-www-form-urlencoded",reader)
checkErr(err)
fmt.Printf("響應(yīng)狀態(tài)碼:%v \n", response.StatusCode)
if response.StatusCode == 200 {
fmt.Println("網(wǎng)絡(luò)請(qǐng)求成功")
defer response.Body.Close()
} else {
fmt.Println("請(qǐng)求失敗",response.Status)
}
}
func checkErr(err error) {
fmt.Println("09-----------")
defer func() {
if ins,ok := recover().(error);ok { // 這種recover的使用方式
fmt.Println("程序出現(xiàn)異常:", ins.Error())
}
}()
if err != nil {
panic(err)
}
}
- webserver 使用http. FileServer ()方法
package main
import "net/http"
func main() {
testFileServer()
}
func testFileServer() {
// 如果該路徑里有index.html 文件距潘,會(huì)優(yōu)先顯示html文件俘侠,否則會(huì)看到文件目錄
http.ListenAndServe(":2003",http.FileServer(http.Dir("./files/")))
}
package main
import (
"fmt"
"net/http"
)
func main() {
// 綁定路徑拴孤,去觸發(fā)方法
http.HandleFunc("/index",indexHandler)
// 綁定端口
// 第一個(gè)參數(shù)為監(jiān)聽地址骆膝,第二個(gè)參數(shù)標(biāo)識(shí)服務(wù)器處理程序蛮瞄,通常為nil浴井, 這意味著服務(wù)端調(diào)用http.DefaultServeMux 進(jìn)行處理
err := http.ListenAndServe(":3013",nil)
fmt.Println(err)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("/index=======")
w.Write([]byte("這是默認(rèn)首頁(yè)"))
}
- 使用http.NewServeMux()方法
- 服務(wù)端獲取客戶端請(qǐng)求數(shù)據(jù)
- golang模板
- map轉(zhuǎn)JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
// 定義一個(gè)map變量并初始化
m := map[string][]string{
"level":{"debug"},
"message":{"file not found","stack overflow"},
}
fmt.Println(m)
// 將map解析成json格式
if data,err := json.Marshal(m);err==nil {
fmt.Printf("%s \n", data)
}
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
// 定義一個(gè)map變量并初始化
m := map[string][]string{
"level":{"debug"},
"message":{"file not found","stack overflow"},
}
fmt.Println(m)
// 將map解析成json格式
if data,err := json.MarshalIndent(m,""," ");err==nil {
fmt.Printf("%s \n", data)
}
}
- 結(jié)構(gòu)體轉(zhuǎn)JSON
package main
import (
"encoding/json"
"fmt"
)
type DebugInfo struct {
Level string
Msg string
author string // 未導(dǎo)出字段不會(huì)被json解析(首字母小寫)
}
func main() {
// 定義一個(gè)結(jié)構(gòu)體切片并初始化
debugInfos := []DebugInfo{
DebugInfo{"debug", `file:"test.txt" not found`, "cynhard"} ,
DebugInfo{"", "logic error", "Gopher"} ,
}
// 將結(jié)構(gòu)體解析成JSON格式
if data,err := json.Marshal(debugInfos);err == nil {
fmt.Printf("%s \n", data)
}
}
package main
import (
"encoding/json"
"fmt"
)
// 可通過結(jié)構(gòu)體標(biāo)簽鸽扁,改變編碼后json字符串的鍵名
type User struct {
Name string `json:"_name"`
Age int `json:"_age"`
Sex uint `json:"-"` // 不解析
Address string // 不改變key標(biāo)簽
}
var user = User {
Name:"Steven",
Age:35,
Sex:1,
Address: "北京海淀區(qū)",
}
func main() {
arr, _ := json.Marshal(user)
fmt.Println(string(arr))
}
package main
import (
"encoding/json"
"fmt"
)
type Point struct {
X,Y int
}
type Circle struct {
Point
Radius int
}
func main() {
// 解析匿名字段
if data, err := json.Marshal(Circle{Point{50,50},25});err == nil {
fmt.Printf("%s \n", data)
}
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
// 定義json格式的字符串
data := `[{"Level":"debug","msg1":"file:\"test.txt\" not found"}, {"Level":"","msg2":"logic error"}]`
var debugInfos []map[string]string
// 將字符串解析成map切片
json.Unmarshal([]byte(data), &debugInfos)
fmt.Println(debugInfos)
}
- json 轉(zhuǎn)結(jié)構(gòu)體
package main
import (
"encoding/json"
"fmt"
)
type DebugInfo struct {
Level string
Msg string
author string // 未導(dǎo)出字段不會(huì)被json解析
}
func (debugInfo DebugInfo) String() string {
return fmt.Sprintf("{Level:%s, Msg:%s}",debugInfo.Level,debugInfo.Msg)
}
func main() {
// 定義json格式的字符串
data := `[{"Level":"debug","Msg":"file:\"test.txt\" not found","author":"abc"}, {"Level":"","Msg":"logic error","author":"ddd"}]`
var debugInfos []DebugInfo
// 將字符串解析成結(jié)構(gòu)體切片
json.Unmarshal([]byte(data), &debugInfos)
fmt.Println(debugInfos)
}
- 解碼時(shí)依然支持結(jié)構(gòu)體字段標(biāo)簽蒜绽,規(guī)則和編碼時(shí)一樣
package main
import (
"encoding/json"
"fmt"
)
type DebugInfo struct {
Level string `json:"level"` // level 解碼成 Level
Msg string `json:"message"` // message 解碼成 Msg
Author string `json:"-"` // 忽略Author
}
func (debugInfo DebugInfo) String() string {
return fmt.Sprintf("{Level:%s, Msg:%s}",debugInfo.Level,debugInfo.Msg)
}
func main() {
// 定義json格式的字符串
data := `[{"level":"debug","message":"file:\"test.txt\" not found","author":"abc"}, {"level":"","message":"logic error","author":"ddd"}]`
var debugInfos []DebugInfo
// 將字符串解析成結(jié)構(gòu)體切片
json.Unmarshal([]byte(data), &debugInfos)
fmt.Println(debugInfos)
}
package main
import (
"encoding/json"
"fmt"
)
type Point struct {
X,Y int
}
type Circle struct {
Point
Radius int
}
func main() {
// 定義json格式字符串
data := `{"X":80,"Y":80,"Radius":60}`
var c Circle
json.Unmarshal([]byte(data), &c)
fmt.Println(c)
}