更新於 2024/05/20閱讀時間約 8 分鐘

[Go]net/HTTP封包

HTTP伺服器端

package main

import (
"net/http"
)

type Refer struct {
handler http.Handler
refer string
}

//實現中介軟體邏輯​
func (this *Refer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Referer() == this.refer {
this.handler.ServeHTTP(w, r)
} else {
w.WriteHeader(403)
}
}

//事件處理​
func myHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("this is handler"))
}

func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}

func main() {
referer := &Refer{
handler: http.HandlerFunc(myHandler),//註冊路由
refer: "www.xxx.com",
}
http.HandleFunc("/hello", hello)//註冊路由
http.ListenAndServe(":8080", referer)//開啟監聽
}


HTTPS伺服器端

創建憑證

//在終端機輸入底下代碼
openssl req -newkey ras:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt


package main

import (
"log"
"net/http"
)

func main() {
// 啟動伺服器
srv := &http.Server{Addr: ":8088", Handler: http.HandlerFunc(handle)}
// 用TLS啟動伺服器,因為我們執行的是http/2,它必須是與TLS一起運作。
log.Printf("Serving on https://0.0.0.0:8088")
log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}

//處理器方法
func handle(w http.ResponseWriter, r *http.Request) {
// 記錄請求協定
log.Printf("Got connection: %s", r.Proto)
// 向客戶發送一則訊息
w.Write([]byte("Hello this is a HTTP/2 message!"))
}


用戶端

GET

package main

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

func main() {
resp, err := http.Get("https://www.xxx.com")
if err != nil {
fmt.Print("err", err)
}
closer := resp.Body
bytes, err := ioutil.ReadAll(closer)
fmt.Println(string(bytes))
}


DELETE

package main

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

func main() {
url := "http://www.xxx.com/comment/add"
payload := strings.NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"xxxx\"}")
req, _ := http.NewRequest("DELETE", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)

defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)

fmt.Println(res)
fmt.Println(string(body))
}


POST

package main

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

func main() {
url := "http://www.xxx.com/comment/add"
body := "{\"userId\":1,\"articleId\":1,\"comment\":\"xxx\"}"
response, err := http.Post(url, "•application/x-www-form-urlencoded", bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("err", err)
}
b, err := ioutil.ReadAll(response.Body)
fmt.Println(string(b))
}


PUT

package main

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

func main() {
url := "http://www.xxx.com/comment/add"
payload := strings.NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"xxx\"}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)

defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)

fmt.Println(res)
fmt.Println(string(body))
}


自定義header

headers := http.Header{"token": {"46r6ttyfy67fy"}}
headers.Add("Accept-Charset", "UTF-8")
headers.Set("Host", "www.xxx.com")
headers.Set("Location", "www.xxx.com")
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.