介绍golang关于http请求和url之间的用法:\
- http-server
import (
"fmt"
"net/http"
)
func main() {
//http://127.0.0.1:8000/go
// 单独写回调函数
http.HandleFunc("/go", myHandler)
//http.HandleFunc("/ungo",myHandler2 )
// addr:监听的地址
// handler:回调函数
http.ListenAndServe("127.0.0.1:8000", nil)
}
// handler函数
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.RemoteAddr, "连接成功")
// 请求方式:GET POST DELETE PUT UPDATE
fmt.Println("method:", r.Method)
// /go
fmt.Println("url:", r.URL.Path)
fmt.Println("header:", r.Header)
fmt.Println("body:", r.Body)
// 回复
w.Write([]byte("www.5lmh.com"))
}
- http参数解析
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
//http-url-request
func main() {
//http-query
apiUrl := "http://127.0.0.1:9090/get?id=1"
// URL param
data := url.Values{}
data.Set("name", "枯藤")
data.Set("age", "18")
u, err := url.ParseRequestURI(apiUrl)
fmt.Printf("%#v \n",u)
if err != nil {
fmt.Printf("parse url requestUrl failed,err:%v\n", err)
}
u.RawQuery += "&"+data.Encode() // URL encode
fmt.Println(u.RawQuery) //id=1&age=18&name=%E6%9E%AF%E8%97%A4
fmt.Println(u.String()) //http://127.0.0.1:9090/get?id=1&age=18&name=%E6%9E%AF%E8%97%A4
http.Get(u.String())
//数据接收解析
data2 :=u.Query()
data2.Get("id")
}
func postDemo(){
//http-body
url := "http://127.0.0.1:9090/post"
// 表单数据
//contentType := "application/x-www-form-urlencoded"
//data := "name=枯藤&age=18"
// json
contentType := "application/json"
data := `{"name":"枯藤","age":18}`
http.Post(url, contentType, strings.NewReader(data))
//http.PostForm("http://5lmh.com/form",
// url.Values{"key": {"Value"}, "id": {"123"}})
//数据接收解析
var r *http.Request
defer r.Body.Close()
// 1. 请求类型是application/x-www-form-urlencoded时解析form数据
r.ParseForm()
fmt.Println(r.PostForm) // 打印form数据
fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))
// 2. 请求类型是application/json时从r.Body读取数据
input,_:=ioutil.ReadAll(r.Body)
//再将body放回去
r.Body = ioutil.NopCloser(bytes.NewBuffer(input))
}
网友评论