Web server development based on Go language

Web server development based on Go language

This article will introduce the use of Go language to develop a simple web server, which will include file upload and download functions.

Prerequisites

  • Go locale
  • a text editor
  • Network Server

Step 1: Write the server.go file

First, we need to write a server.gofile called , which will contain the code for our Go web server.

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!"))
}

In the above code, we imported net/httpthe package, which contains everything needed for the Go web server. In mainthe function, we set up the route and started an HTTP server. In rootthe function, we return a simple string Hello, world!.

Step 2: Add file upload function

io/ioutilThe file upload function can be implemented using the native Go language library.

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))
}

In the above code, we have added a new uploadfunction, which will read the uploaded file and then store it in the specified location on the server. At the same time, we also rootadded an upload form to the function so that users can upload files.

Step 3: Add file download function

net/httpThe file download function can also be implemented using Go language packages.

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))
}

In the above code, we add a new downloadfunction, which will set the file header, read the file content, and return the file content to the client. At the same time, we also rootadd a link to the function for accessing downloadthe function.

Summarize

This article describes how to use the Go language to develop a web server and add file upload and download functions to it. Through this article, you should have a deeper understanding of developing web servers with Go language, and you can also try to implement more functions yourself to make the website more complete.

Guess you like

Origin blog.csdn.net/weixin_50814640/article/details/129446849