基于Go语言的Web服务器开发

基于Go语言的Web服务器开发

本文将介绍使用Go语言来开发一个简单的Web服务器,其中将包括文件上传和下载功能。

必备条件

  • Go语言环境
  • 一个文本编辑器
  • 网络服务器

步骤一:编写server.go文件

首先,我们需要编写一个名为server.go的文件,它将包含我们的Go语言Web服务器的代码。

package main

import (
	"net/http"
)

func main() {
    
    
	// 设置路由
	http.HandleFunc("/", root)
	// 启动服务
	http.ListenAndServe(":8080", nil)
}

func root(w http.ResponseWriter, req *http.Request) {
    
    
	// 根路由,输出Hello, World!
	w.Write([]byte("Hello, World!"))
}

上面的代码中,我们导入了net/http包,它包含了Go语言的网络服务器所需的一切。在main函数中,我们设置了路由,并且启动了一个HTTP服务器,在root函数中,我们返回了一个简单的字符串Hello, world!

步骤二:添加文件上传功能

文件上传功能可以使用Go语言原生的io/ioutil库来实现。

package main 

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

// 新增upload函数
func upload(w http.ResponseWriter, req *http.Request) {
    
    
	// 读取请求文件
	file, _, err := req.FormFile("uploadFile")
	if err != nil {
    
    
		w.Write([]byte(err.Error()))
		return
	}
	defer file.Close()

	// 将文件存入到服务器指定位置
	data, err := ioutil.ReadAll(file)
	if err != nil {
    
    
		w.Write([]byte(err.Error()))
		return
	}
	err = ioutil.WriteFile("./uploads/upload.dat", data, 0666)
	if err != nil {
    
    
		w.Write([]byte(err.Error()))
		return
	}
	w.Write([]byte("文件上传成功!"))
}

func main() {
    
    
	http.HandleFunc("/", root)
	// 新增upload路由
	http.HandleFunc("/upload", upload)
	http.ListenAndServe(":8080", nil)
}

func root(w http.ResponseWriter, req *http.Request) {
    
    
	// 返回上传表单
	html := `<form action="/upload" method="post" enctype="multipart/form-data">
				<input type="file" name="uploadFile" />
				<input type="submit" value="上传文件" />
			</form>`
	w.Write([]byte(html))
}

上面的代码中,我们新增了一个upload函数,它会读取上传的文件,然后将其存放到服务器指定位置。同时,我们还在root函数中添加了一个上传表单,以便用户可以上传文件。

步骤三:添加文件下载功能

文件下载功能也可以使用Go语言的net/http包来实现。

package main

import (
	"io"
	"net/http"
)

// 新增download函数
func download(w http.ResponseWriter, req *http.Request) {
    
    
	// 设置文件头
	w.Header().Add("Content-Disposition", "attachment; filename=file.dat")
	w.Header().Add("Content-Type", "application/octet-stream")
	// 读取文件内容
	file, err := ioutil.ReadFile("./uploads/upload.dat")
	if err != nil {
    
    
		w.Write([]byte(err.Error()))
		return
	}
	// 返回文件内容
	io.WriteString(w, string(file))
}

func main() {
    
    
	http.HandleFunc("/", root)
	http.HandleFunc("/upload", upload)
	// 新增download路由
	http.HandleFunc("/download", download)
	http.ListenAndServe(":8080", nil)
}

func root(w http.ResponseWriter, req *http.Request) {
    
    
	html := `<form action="/upload" method="post" enctype="multipart/form-data">
				<input type="file" name="uploadFile" />
				<input type="submit" value="上传文件" />
			</form>
			<a href="/download">下载文件</a>`
	w.Write([]byte(html))
}

上面的代码中,我们新增一个download函数,它会设置文件头,读取文件内容,并且将文件内容返回给客户端,同时,我们还在root函数中添加一个链接,用于访问download函数。

总结

本文介绍了如何使用Go语言开发一个Web服务器,并在其中添加文件上传和下载功能。通过本文,你应该对Go语言开发Web服务器有了更深入的了解,也可以尝试自己去实现更多的功能,让网站更加完善。

猜你喜欢

转载自blog.csdn.net/weixin_50814640/article/details/129446849