type
status
date
slug
summary
tags
category
icon
password

基本使用

发送HTTP请求

  • 普通的请求
    • resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
      拿到响应之后需要关闭Response.Body:
      resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // ...
  • 自定义Header
    • client := &http.Client{ CheckRedirect: redirectPolicyFunc, } req, err := http.NewRequest("GET", "http://example.com", nil) req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req)
  • 连接控制,比如超时时间等
    • tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com")

响应请求

  • 简单响应
    • http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", nil))
  • 自定义控制响应
    • s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe())

一个简单的Demo

package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { http.HandleFunc("/", home) fmt.Println("url: http://localhost:8080 ") err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe", err) } } // 默认处理 func home(writer http.ResponseWriter, request *http.Request) { http.Get("https://api.github.com/users/jiangkang") client := &http.Client{} req, _ := http.NewRequest(http.MethodGet, "https://api.github.com/users/jiangkang", nil) req.Header.Add("Accept", "application/vnd.github.v3+json") response, _ := client.Do(req) body, _ := ioutil.ReadAll(response.Body) writer.Write(body) }

处理表单数据/Query数据

对于表单数据和Query中的参数,都可以使用request.ParseForm()进行解析.
func login(writer http.ResponseWriter, request *http.Request) { if request.Method == http.MethodGet { t,_ := template.ParseFiles("html/login.html") t.Execute(writer,nil) } else if request.Method == http.MethodPost { request.ParseForm() username := request.Form.Get("username") password := request.Form.Get("password") fmt.Fprintf(writer,"登陆成功:username: %s \n, password: %s",username,password) } }
request.Form是一个map[string][]string类型,对应Java的 Map<String,Array<String>>.
使用form.Get()可以获取单个值.
….未完待续
Go中的init方法Go-处理json
姜康
姜康
一个软件工程师
公告
type
status
date
slug
summary
tags
category
icon
password
🎉博客网站重新制作了🎉
👏欢迎更新体验👏