国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

這篇具有很好參考價(jià)值的文章主要介紹了Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

? ? ?最近再看Go語(yǔ)言web編程,go語(yǔ)言搭建Web服務(wù)器,既可以用go原生的net/http包,也可以用gin/fasthttp/fiber等這些Web框架。本博客使用net/http模塊編寫了一個(gè)簡(jiǎn)單的登錄驗(yàn)證和文件上傳的功能,在此做個(gè)簡(jiǎn)單記錄。

目錄

1.文件目錄結(jié)構(gòu)

2.編譯運(yùn)行

3.用戶登錄

?4.文件上傳

5.mime/multipart模擬form表單上傳文件


代碼如下:

package main

import (
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
)

/*
go運(yùn)行方式:
(1)解釋運(yùn)行
go run main.go

(2)編譯運(yùn)行
--使用默認(rèn)名
go build main.go
./main
--指定可執(zhí)行程序名
go build -o test main.go
./test
*/

// http://127.0.0.1:8181/login
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method", r.Method)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.html")
		t.Execute(w, nil)
		/*
			//字符串拼裝表單
				html := `<html>
					<head>
					<title>上傳文件</title>
					</head>
					<body>
					<form enctype="multipart/form-data" action="http://localhost:8181/upload" method="post">
						<input type="file" name="uploadfile" />
						<input type="hidden" name="token" value="{
						{.}}" />
						<input type="submit" value="upload" />
					</form>
					</body>
					</html>`
				crutime := time.Now().Unix()
				h := md5.New()
				io.WriteString(h, strconv.FormatInt(crutime, 10))
				token := fmt.Sprintf("%x", h.Sum(nil))
				t := template.Must(template.New("test").Parse(html))
				t.Execute(w, token)
		*/
	} else {
		r.ParseForm()
		fmt.Println("username", r.Form["username"])
		fmt.Println("password", r.Form["password"])
		fmt.Fprintf(w, "登錄成功")
	}
}

// http://127.0.0.1:8181/upload
func upload(writer http.ResponseWriter, r *http.Request) {
	//表示maxMemory,調(diào)用ParseMultipart后,上傳的文件存儲(chǔ)在maxMemory大小的內(nèi)存中,
	//如果大小超過maxMemory,剩下部分存儲(chǔ)在系統(tǒng)的臨時(shí)文件中
	r.ParseMultipartForm(32 << 10)
	//根據(jù)input中的name="uploadfile"來(lái)獲得上傳的文件句柄
	file, header, err := r.FormFile("uploadfile")
	if err != nil {
		fmt.Fprintf(writer, "上傳出錯(cuò)")
		fmt.Println(err)
		return
	}
	defer file.Close()
	/*
		fmt.Printf("Uploaded File: %+v\n", header.Filename)
		fmt.Printf("File Size: %+v\n", header.Size)
				// 注意此處的header.Header是textproto.MIMEHeader類型 ( map[string][]string )
		fmt.Printf("MIME Type: %+v\n", header.Header.Get("Content-Type"))
		// 將文件保存到服務(wù)器指定的目錄(* 用來(lái)隨機(jī)數(shù)的占位符)
		tempFile, err := ioutil.TempFile("uploads", "*"+header.Filename)
	*/
	fmt.Println("handler.Filename", header.Filename)
	f, err := os.OpenFile("./filedir/"+header.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println(err)
		fmt.Fprintf(writer, "上傳出錯(cuò)")
		return
	}
	defer f.Close()
	io.Copy(f, file)
	fmt.Fprintf(writer, "上傳成功")
}

func common_handle() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello world !"))
	})
	http.HandleFunc("/login", login)
	http.HandleFunc("/upload", upload)
}

func main1() {
	common_handle()
	//監(jiān)聽8181端口
	err := http.ListenAndServe(":8181", nil)
	if err != nil {
		log.Fatal("err:", err)
	}
}

// 聲明helloHandler
type helloHandler struct{}

// 定義helloHandler
func (m11111 *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello world, this is my first golang programe !"))
}

func welcome(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Welcome to golang family !"))
}

func main2() {
	a := helloHandler{}

	//使用http.Handle
	http.Handle("/hello", &a)
	http.Handle("/welcome", http.HandlerFunc(welcome))

	common_handle()

	server := http.Server{
		Addr:    "127.0.0.1:8181",
		Handler: nil, // 對(duì)應(yīng)DefaultServeMux路由
	}
	server.ListenAndServe()
}

func main() {
	main2()
}

login.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8"/>
		<title>歡迎進(jìn)入首頁(yè)</title>
	</head>
	<body>
		<h3>登錄測(cè)試</h3>
		<hr/>

		<form action="http://localhost:8181/login" method="post">
			<table border=0 title="測(cè)試">
				<tr>
					<td>用戶名:</td>
					<td><input type="text" name="username"></td>
				</tr>
				<tr>
					<td>密碼:</td>
					<td><input type="password" name="password"></td>
				</tr>
				<tr>
					<td colspan=2>
						<input type="reset" />
						<input type="submit" value="登錄" />
					</td>
				</tr>
			</table>
		</form>
		<br>
		<h3>文件上傳測(cè)試</h3>
		<hr/>
		<form action="http://localhost:8181/upload" method="post" enctype="multipart/form-data">
			<input type="file" name="uploadfile"/>
			<input type="submit" value="upload">
		</form>
	</body>
</html>

1.文件目錄結(jié)構(gòu)

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

2.編譯運(yùn)行

?Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

3.用戶登錄

http://127.0.0.1:8181/login

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

?4.文件上傳

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

?Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

5.mime/multipart模擬form表單上傳文件

? ? ? ?使用mime/multipart包,可以將multipart/form-data數(shù)據(jù)解析為一組文件和表單字段,或者使用multipart.Writer將文件和表單字段寫入HTTP請(qǐng)求體中。

? ? ? ?以下例子中首先打開要上傳的文件,然后創(chuàng)建一個(gè)multipart.Writer,用于構(gòu)造multipart/form-data格式的請(qǐng)求體。我們使用CreateFormFile方法創(chuàng)建一個(gè)multipart.Part,用于表示文件字段,將文件內(nèi)容復(fù)制到該P(yáng)art中。我們還使用WriteField方法添加其他表單字段。然后,我們關(guān)閉multipart.Writer,以便寫入Content-Type和boundary,并使用NewRequest方法創(chuàng)建一個(gè)HTTP請(qǐng)求。我們將Content-Type設(shè)置為multipart/form-data,并使用默認(rèn)的HTTP客戶端發(fā)送請(qǐng)求。最后,我們讀取并處理響應(yīng)。

關(guān)于什么是multipart/form-data?
multipart/form-data的基礎(chǔ)是post請(qǐng)求,即基于post請(qǐng)求來(lái)實(shí)現(xiàn)的
multipart/form-data形式的post與普通post請(qǐng)求的不同之處體現(xiàn)在請(qǐng)求頭,請(qǐng)求體2個(gè)部分
1)請(qǐng)求頭:
必須包含Content-Type信息,且其值也必須規(guī)定為multipart/form-data,同時(shí)還需要規(guī)定一個(gè)內(nèi)容分割符用于分割請(qǐng)求體中不同參數(shù)的內(nèi)容(普通post請(qǐng)求的參數(shù)分割符默認(rèn)為&,參數(shù)與參數(shù)值的分隔符為=)。
具體的頭信息格式如下:
Content-Type: multipart/form-data; boundary=${bound}
其中${bound} 是一個(gè)占位符,代表我們規(guī)定的具體分割符;可以自己任意規(guī)定,但為了避免和正常文本重復(fù)了,盡量要使用復(fù)雜一點(diǎn)的內(nèi)容。如:—0016e68ee29c5d515f04cedf6733
比如有一個(gè)body為:
--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=text\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nwords words words wor=\r\nds words words =\r\nwords words wor=\r\nds words words =\r\nwords words\r\n--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=submit\r\n\r\nSubmit\r\n--0016e68ee29c5d515f04cedf6733--

2)請(qǐng)求體:
它也是一個(gè)字符串,不過和普通post請(qǐng)求體不同的是它的構(gòu)造方式。普通post請(qǐng)求體是簡(jiǎn)單的鍵值對(duì)連接,格式如下:
k1=v1&k2=v2&k3=v3
而multipart/form-data則是添加了分隔符、參數(shù)描述信息等內(nèi)容的構(gòu)造體。
具體格式如下:
--${bound}
Content-Disposition: form-data; name="Filename" //第一個(gè)參數(shù),相當(dāng)于k1;然后回車;然后是參數(shù)的值,即v1
HTTP.pdf //參數(shù)值v1
--${bound} //其實(shí)${bound}就相當(dāng)于上面普通post請(qǐng)求體中的&的作用
Content-Disposition: form-data; name="file000"; filename="HTTP協(xié)議詳解.pdf" //這里說(shuō)明傳入的是文件,下面是文件提
Content-Type: application/octet-stream //傳入文件類型,如果傳入的是.jpg,則這里會(huì)是image/jpeg %PDF-1.5
file content
%%EOF
--${bound}
Content-Disposition: form-data; name="Upload"
Submit Query
--${bound}--
都是以${bound}為開頭的,并且最后一個(gè)${bound}后面要加—

test.go

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	// 需要上傳的文件路徑
	filePath := "image_2023_06_29T11_46_39_023Z.png"

	// 打開要上傳的文件
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("Failed to open file:", err)
		return
	}
	defer file.Close()

	// 創(chuàng)建multipart.Writer,用于構(gòu)造multipart/form-data格式的請(qǐng)求體
	var requestBody bytes.Buffer
	multipartWriter := multipart.NewWriter(&requestBody)

	// 創(chuàng)建一個(gè)multipart.Part,用于表示文件字段
	part, err := multipartWriter.CreateFormFile("uploadfile", filepath.Base(filePath))
	if err != nil {
		fmt.Println("Failed to create form file:", err)
		return
	}

	// 將文件內(nèi)容復(fù)制到multipart.Part中
	_, err = io.Copy(part, file)
	if err != nil {
		fmt.Println("Failed to copy file content:", err)
		return
	}

	// 添加其他表單字段
	multipartWriter.WriteField("title", "My file")

	// 關(guān)閉multipart.Writer,以便寫入Content-Type和boundary
	err = multipartWriter.Close()
	if err != nil {
		fmt.Println("Failed to close multipart writer:", err)
		return
	}

	// 創(chuàng)建HTTP請(qǐng)求
	req, err := http.NewRequest("POST", "http://127.0.0.1:8181/upload", &requestBody)
	if err != nil {
		fmt.Println("Failed to create request:", err)
		return
	}

	// 設(shè)置Content-Type為multipart/form-data
	req.Header.Set("Content-Type", multipartWriter.FormDataContentType())

	// 發(fā)送HTTP請(qǐng)求
	client := http.DefaultClient
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return
	}
	defer resp.Body.Close()

	// 處理響應(yīng)
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Failed to read response:", err)
		return
	}
	fmt.Println("Response:", string(respBody))
}

編譯執(zhí)行:

go build test.go?

./test?

運(yùn)行結(jié)果展示:

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能

Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-510020.html

到了這里,關(guān)于Go語(yǔ)言使用net/http實(shí)現(xiàn)簡(jiǎn)單登錄驗(yàn)證和文件上傳功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Go語(yǔ)言 -- Web開發(fā)基礎(chǔ)學(xué)習(xí) net/http包

    Go語(yǔ)言 -- Web開發(fā)基礎(chǔ)學(xué)習(xí) net/http包

    Go 是一個(gè)開源的編程語(yǔ)言,它能讓構(gòu)造簡(jiǎn)單、可靠且高效的軟件變得容易。 Go語(yǔ)言最擅長(zhǎng)的領(lǐng)域就是Web開發(fā),此貼是本人入門完go語(yǔ)法基礎(chǔ)后學(xué)習(xí)Web開發(fā)的學(xué)習(xí)筆記。 新建go文件hello_world.go 寫入: 在命令行運(yùn)行: go run ./hello_world.go 可以發(fā)現(xiàn)控制臺(tái)輸出以下信息 通過上述代碼

    2024年02月06日
    瀏覽(22)
  • 【設(shè)計(jì)模式】使用 go 語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單工廠模式

    最近在看《大話設(shè)計(jì)模式》,這本書通過對(duì)話形式講解設(shè)計(jì)模式的使用場(chǎng)景,有興趣的可以去看一下。 第一篇講的是 簡(jiǎn)單工廠模式 ,要求輸入兩個(gè)數(shù)和運(yùn)算符號(hào),得到運(yùn)行結(jié)果。 這個(gè)需求不難,難就難在類要怎么設(shè)計(jì),才能達(dá)到可復(fù)用、維護(hù)性強(qiáng)、可拓展和靈活性高。 運(yùn)

    2024年02月05日
    瀏覽(31)
  • asp.net mvc實(shí)現(xiàn)系統(tǒng)登錄及驗(yàn)證功能

    asp.net mvc實(shí)現(xiàn)系統(tǒng)登錄及驗(yàn)證功能

    在網(wǎng)上購(gòu)物或者實(shí)際的使用過程中經(jīng)常遇到這樣的一個(gè)場(chǎng)景:你必須輸入用戶米/密碼,進(jìn)行登錄。登錄完成后,界面自動(dòng)跳轉(zhuǎn)到之前的界面或者主頁(yè)。具體下面的三個(gè)圖所示。 在ASP.NET MVC中有個(gè)功能是身份認(rèn)證(就是使用用戶名和密碼登錄的問題),以及使用角色登錄的功能

    2024年02月02日
    瀏覽(23)
  • SpringBoot實(shí)現(xiàn)簡(jiǎn)單的登錄驗(yàn)證碼

    SpringBoot實(shí)現(xiàn)簡(jiǎn)單的登錄驗(yàn)證碼

    參考了一些資料,完成了這個(gè)驗(yàn)證碼的功能,下面記錄一下功能的實(shí)現(xiàn)過程。 后臺(tái)生成驗(yàn)證碼圖片,將圖片傳到前臺(tái)。 后臺(tái)在session中保存驗(yàn)證碼內(nèi)容。 前臺(tái)輸入驗(yàn)證碼后傳到后臺(tái)在后臺(tái)取出session中保存的驗(yàn)證碼進(jìn)行校驗(yàn)。 1、建一個(gè)config 我是建了一個(gè)名叫KaptchaConfig的con

    2024年02月10日
    瀏覽(9)
  • Curl- go的自帶包 net/http實(shí)現(xiàn)

    case http 包中的 Request 發(fā)送請(qǐng)求的步驟:1. 創(chuàng)建客戶端 2. 發(fā)送請(qǐng)求 3. 接受響應(yīng) http.NewRequest method get,post,delete,put url body :可以是多種形式的數(shù)據(jù)包含在請(qǐng)求體中 我們可以看出這個(gè) : body 是一個(gè) io.Reader 所以 Request 的請(qǐng)求體就是字節(jié)流。所以制定編碼方式-》用 header 指定

    2024年01月20日
    瀏覽(18)
  • JavaGui實(shí)現(xiàn)登錄界面編寫+實(shí)現(xiàn)賬號(hào)密碼驗(yàn)證登錄+文件存儲(chǔ)

    JavaGui實(shí)現(xiàn)登錄界面編寫+實(shí)現(xiàn)賬號(hào)密碼驗(yàn)證登錄+文件存儲(chǔ)

    目錄 標(biāo)題一: 登錄界面編寫 標(biāo)題二;登錄界面之注冊(cè)(一個(gè)類)編寫? 標(biāo)題三:登錄界面之登錄編寫? 在登錄界面這里,我們先編寫一個(gè)登錄界面出來(lái),這只是一個(gè)界面,還沒有實(shí)現(xiàn)驗(yàn)證賬號(hào)密碼和注冊(cè)的功能,但得有這個(gè)界面做媒介 。 界面如下: ? 1.登陸界面代碼在這里

    2024年02月08日
    瀏覽(21)
  • go語(yǔ)言簡(jiǎn)單實(shí)現(xiàn)區(qū)塊鏈

    ????????在本文中,我們將使用Go語(yǔ)言來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的區(qū)塊鏈系統(tǒng),包括區(qū)塊生成、交易處理和區(qū)塊打印、保存區(qū)塊鏈等功能。 在開始之前,先確保計(jì)算機(jī)上安裝了以下內(nèi)容: Go編程語(yǔ)言:您可以從Go官方網(wǎng)站下載并安裝Go。 Go開發(fā)環(huán)境:設(shè)置Go開發(fā)環(huán)境,包括文本編輯器

    2024年04月16日
    瀏覽(26)
  • Apinto 網(wǎng)關(guān): Go語(yǔ)言實(shí)現(xiàn) HTTP 轉(zhuǎn) gRPC

    Apinto 網(wǎng)關(guān): Go語(yǔ)言實(shí)現(xiàn) HTTP 轉(zhuǎn) gRPC

    gRPC ?是由 Google 開發(fā)的一個(gè)高性能、通用的開源RPC框架,主要面向移動(dòng)應(yīng)用開發(fā)且基于? HTTP/2 ?協(xié)議標(biāo)準(zhǔn)而設(shè)計(jì),同時(shí)支持大多數(shù)流行的編程語(yǔ)言。 gRPC ?基于? HTTP/2 ?協(xié)議傳輸,? HTTP/2? 相比? HTTP1.x 有以下優(yōu)勢(shì): 采用二進(jìn)制格式傳輸協(xié)議,支持多路復(fù)用。 支持通過同一個(gè)連

    2024年02月07日
    瀏覽(24)
  • 使用Go語(yǔ)言編寫HTTP代理服務(wù)器

    使用Go語(yǔ)言編寫HTTP代理服務(wù)器

    在Go語(yǔ)言中,編寫一個(gè)HTTP代理服務(wù)器相對(duì)簡(jiǎn)單且直觀。代理服務(wù)器的主要職責(zé)是接收客戶端的請(qǐng)求,然后將請(qǐng)求轉(zhuǎn)發(fā)到目標(biāo)服務(wù)器,再將目標(biāo)服務(wù)器的響應(yīng)返回給客戶端。下面是一個(gè)簡(jiǎn)單的示例,展示如何使用Go語(yǔ)言編寫一個(gè)基本的HTTP代理服務(wù)器: go 復(fù)制代碼 package ?main i

    2024年01月18日
    瀏覽(19)
  • 【go語(yǔ)言開發(fā)】redis簡(jiǎn)單使用

    【go語(yǔ)言開發(fā)】redis簡(jiǎn)單使用

    本文主要介紹redis安裝和使用。首先安裝redis依賴庫(kù),這里是v8版本;然后連接redis,完成基本配置;最后測(cè)試封裝的工具類 歡迎大家訪問個(gè)人博客網(wǎng)址:https://www.maogeshuo.com,博主努力更新中… 參考文件: Yaml文件配置,Config使用 Log日志封裝 常用工具類封裝 命令行安裝redis

    2024年03月12日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包