Go.网络篇-2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go.网络篇-2相关的知识,希望对你有一定的参考价值。

package main

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

const (
	UPLOAD_DIR = "./upload"
)

func main(){
	http.HandleFunc("/",listHandler)
	http.HandleFunc("/upload",uploadHandler)	
	http.HandleFunc("/view",viewHandler)	
	err := http.ListenAndServe("127.0.0.1:8080",nil)
	
	if err != nil {
		log.Fatal("ListenAndServe:", err.Error())
	}	
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method == "GET" {
		io.WriteString(w,"<html><form method=\"POST\" action=\"/upload\" enctype=\"multipart/form-data\">" + 
						"Choose an image to upload: <input name=\"image\" type=\"file\" />" +
						"<input type=\"submit\" value=\"Upload\" /></form></html>")		
	}

	if r.Method == "POST" {

		f,h,err := r.FormFile("image")

		if err != nil {
			http.Error(w,err.Error(),http.StatusInternalServerError)
			return
		}

		filename := h.Filename
		defer f.Close()

		t,err := os.Create(UPLOAD_DIR + "/" + filename)

		if err != nil {
			http.Error(w,err.Error(),http.StatusInternalServerError)
			return
		}

		defer t.Close()

		if _,err := io.Copy(t,f); err != nil {
			http.Error(w,err.Error(),http.StatusInternalServerError)
			return
		}

		http.Redirect(w,r,"/view?id="+filename,http.StatusFound)
	}

	return
}

func viewHandler(w http.ResponseWriter, r *http.Request){

	id := r.FormValue("id")
	path := UPLOAD_DIR + "/" + id 

	if !hasfile(path) {
		http.NotFound(w,r)
		return
	}

	w.Header().Set("Content-Type","image")
	http.ServeFile(w,r,path)
}

func hasfile(path string) bool {

	_,err := os.Stat(path)
	if err == nil {
		return true
	}

	return os.IsExist(err)
}

func listHandler(w http.ResponseWriter, r *http.Request){
	fileInfo,err := ioutil.ReadDir("./upload")

	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
		return
	}

	var html string 
	html += "<html><ol>"
	for _,info := range fileInfo {
		id := info.Name()
		html += "<li><a href=\"view?id=" + id + "\">" + id + "</a></li>"
	}
	html += "</ol></html>"

	io.WriteString(w,html)
}

## 简单的图片管理网站

以上是关于Go.网络篇-2的主要内容,如果未能解决你的问题,请参考以下文章

go 网络请求篇二

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础

解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段

golang代码片段(摘抄)

go+系列数组集合基础篇

配置 VScode 编辑器 (前端篇)