[Go]處理請求

小黑
發佈於後端
2024/01/02閱讀時間約 13 分鐘

Request內容

package main

import (
"fmt"
"log"
"net/http"
"strings"
)

func request(w http.ResponseWriter, r *http.Request) {
//這些資訊是輸出到伺服器端的列印訊息
fmt.Println("Request解析")
//HTTP方法
fmt.Println("method", r.Method)
//RequestURI是被客戶端傳送到服務端的請求的請求行中未修改的請求URI
fmt.Println("RequestURI:", r.RequestURI)
//URL類型,下方分別列出URL的各成員
fmt.Println("URL_path", r.URL.Path)
fmt.Println("URL_RawQuery", r.URL.RawQuery)
fmt.Println("URL_Fragment", r.URL.Fragment)
//協定版本
fmt.Println("proto", r.Proto)
fmt.Println("protomajor", r.ProtoMajor)
fmt.Println("protominor", r.ProtoMinor)
//HTTP請求的頭域
for k, v := range r.Header {
for _, vv := range v {
fmt.Println("header key:" + k + " value:" + vv)
}
}
//判斷是否multipart方式
isMultipart := false
for _, v := range r.Header["Content-Type"] {
if strings.Index(v, "multipart/form-data") != -1 {
isMultipart = true
}
}
//解析body
if isMultipart == true {
r.ParseMultipartForm(128)
fmt.Println("解析方式:ParseMultipartForm")
} else {
r.ParseForm()
fmt.Println("解析方式:ParseForm")
}
//body內容長度
fmt.Println("ContentLength", r.ContentLength)
//是否在回覆請求後關閉連接
fmt.Println("Close", r.Close)
//HOSt
fmt.Println("host", r.Host)
//該請求的來源位址
fmt.Println("RemoteAddr", r.RemoteAddr)

fmt.Fprintf(w, "hello, let's go!")
//這個寫入到w的是輸出到客戶端的
}
func main() {
http.HandleFunc("/hello", request)
err := http.ListenAndServe(":8081", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}


URL內容

package main

import "net/url"

func main() {
path := "http://lcoalhost:8082/article?id=1"
p, _ := url.Parse(path) // 解析url
println(p.Host)//lcoalhost:8082
println(p.User)//0x0
println(p.RawQuery)//id=1
println(p.RequestURI())///article?id=1
}


請求的內容

package main

import (
"fmt"
"net/http"
)

func getBody(w http.ResponseWriter, r *http.Request) {
//取得請求訊息的內容長度
len := r.ContentLength
//新建一個位元組切片,長度與請求封包的內容長度相同
body := make([]byte, len)
//讀取r的請求主體,並將具體內容讀入body中
r.Body.Read(body)
//將位元組切片內容寫入對應報文
fmt.Fprintln(w, string(body))
}
func main() {
http.HandleFunc("/getBody", getBody)
err := http.ListenAndServe(":8082", nil)
if err != nil {
fmt.Println(err)
}
}


Form與PostForm

package main

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

func process(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("form.html")
t.Execute(w, nil)
} else {
r.ParseForm()//語法分析
fmt.Fprintln(w, "表單鍵值對和URL鍵值對:", r.Form)
fmt.Fprintln(w, "表單鍵值對:", r.PostForm)
}
}

func main() {
http.HandleFunc("/", process)
http.ListenAndServe(":8089", nil)
}


MultipartForm

package main

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

func multiProcess(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("form.html")
t.Execute(w, nil)
} else {
r.ParseMultipartForm(1024)//從表單中提取多少位元組的數據
fmt.Fprintln(w,"表单键值对:", r.MultipartForm)
}
}

func main() {
http.HandleFunc("/", multiProcess)
http.ListenAndServe(":8089", nil)
}


上傳檔案

package main

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

//上傳
func upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("upload.html")
t.Execute(w, nil)
} else {
r.ParseMultipartForm(4096)
fileHeader := r.MultipartForm.File["uploaded"][0]//取得名為"uploaded"的第一個檔案頭

file, err := fileHeader.Open()//取得文件
if err != nil {
fmt.Println("error")
return
}
data, err := ioutil.ReadAll(file)//讀取文件
if err != nil {
fmt.Println("error!")
return
}
fmt.Fprintln(w, string(data))
}
}

func main() {
http.HandleFunc("/", upload)
http.ListenAndServe(":8089", nil)
}


WriteHeader()與Header()

package main

import (
"fmt"
"net/http"
)

func Redirect(w http.ResponseWriter, r *http.Request) {
//設定一個301重定向
w.Header().Set("Location", "https://www.xxx.com")
w.WriteHeader(301)
}

func main() {
http.HandleFunc("/redirect", Redirect)
err := http.ListenAndServe(":8086", nil)
if err != nil {
fmt.Println(err)
}
}

這邊要注意w.Header().Set()與w.WriteHeader()的使用順序。


Write()

字串

package main

import (
"fmt"
"net/http"
)

func Welcome(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Go go!"))
}

func main() {
http.HandleFunc("/welcome", Welcome)
err := http.ListenAndServe(":8086", nil)
if err != nil {
fmt.Println(err)
}
}


HTML

package main

import (
"fmt"
"net/http"
)

func Home(w http.ResponseWriter, r *http.Request) {
html := `<html>
<head>
<title>Write()內容為HTML</title>
</head>
<body>
<h1>Go go go
</body>
</html>`
w.Write([]byte(html))
}

func main() {
http.HandleFunc("/", Home)
err := http.ListenAndServe(":8086", nil)
if err != nil {
fmt.Println(err)
}
}


JSON

package main

import (
"encoding/json"
"fmt"
"net/http"
)

type JsonData struct {
Message string `json:"message"`
}
func Hello(w http.ResponseWriter, r *http.Request) {
//返回JSON格式
jsonData := JsonData{
"Go go",
}
message, _ := json.Marshal(jsonData)
w.Header().Set("Content-Type", "application/json")
w.Write(message)
}

func main() {
http.HandleFunc("/", Hello)
err := http.ListenAndServe(":8086", nil)
if err != nil {
fmt.Println(err)
}
}





7會員
78內容數
嗨,我是一名程式設計師,會在這分享開發與學習紀錄。
留言0
查看全部
發表第一個留言支持創作者!