Go语言中http和mysql的实现代码

2020-01-28 13:43:47刘景俊

http 编程

Go 原生支持http:

import "net/http"

Go 的http服务性能和nginx比较接近:

就是说用Go写的Web程序上线,程序前面不需要再部署nginx的Web服务器,这里省掉的是Web服务器。如果服务器上部署了多个Web应用,还是需要反向代理的,一般这也是nginx或apache。

几行代码就可以实现一个web服务:


package main
import (
 "fmt"
 "net/http"
)
func Hello(w http.ResponseWriter, r *http.Request) {
 fmt.Println(*r)
 fmt.Fprintf(w, "Hello World")
}
func main() {
 http.HandleFunc("/", Hello)
 err := http.ListenAndServe("0.0.0.0:8000", nil)
 if err != nil {
  fmt.Println("http Listen failed")
 }
}

http client

http 常见的请求方法:

Get请求 Post请求 Put请求 Delete请求 Head请求

Get 请求

使用Get请求网站的示例:


package main

import (
 "fmt"
 "io/ioutil"
 "net/http"
)

func main() {
 res, err := http.Get("http://edu.51cto.com")
 if err != nil {
  fmt.Println("http get ERRPR:", err)
  return
 }
 data, err := ioutil.ReadAll(res.Body)
 if err != nil {
  fmt.Println("get data ERROR:", err)
  return
 }
 fmt.Println(string(data))
}

Head请求

Head请求只返回响应头。如果只想要获取一些状态信息的话,可以用Head请求。这样避免返回响应体,响应体的数据是比较多的,适合做监控。Head请求的示例:


package main
import (
 "fmt"
 "net/http"
)
var urls = []string{
 "http://×××w.baidu.com",
 "http://×××w.google.com",
 "http://×××w.sina.com.cn",
 "http://×××w.163.com",
}
func main() {
 for _, v := range urls {
  resp, err := http.Head(v)
  if err != nil {
   fmt.Println("Head request ERROR:", err)
   continue
  }
  fmt.Println(resp.Status)
 }
}

http 常见状态码

http.StatusContinue = 100

http.StatusOK = 200

http.StatusFound = 302 跳转

http.StatusBadRequest = 400 非法请求

http.StatusUnanthorized = 401 没有权限

http.StatusForbidden = 403 禁止访问

http.Status.NotFound = 404 页面不存在

http.StatusInternalServerError = 500 内部错误

处理form表单


package main

import (
 "fmt"
 "io"
 "net/http"
)

const form = `
<html>
<body>
<form action="#" method="post" name="bar">
 <input type="text" name="in" />
 <input type="text" name="in" />
 <input type="submit" value="Submit" />
</form>
</body>
</html>`

func FormServer(w http.ResponseWriter, request *http.Request) {
 w.Header().Set("content-Type", "text/html")
 switch request.Method {
 case "GET":
  io.WriteString(w, form)
 case "POST":
  request.ParseForm()
  io.WriteString(w, request.Form["in"][0]) // 注意上面的2个input的name是一样的
  io.WriteString(w, request.Form["in"][1]) // 所以这是一个数组
  io.WriteString(w, "</br>")
  io.WriteString(w, request.FormValue("in")) // 一般去一个值,就用这个方法
 }
}

func main() {
 http.HandleFunc("/form", FormServer)
 if err := http.ListenAndServe(":8000", nil); err != nil {
  fmt.Println("监听端口ERROR:", err)
 }
}