Go学习之旅之--实现一个小的本地存储

package main

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

const storeDir = "/Users/haohaiwei/test/"
func Handler(w http.ResponseWriter, r *http.Request) {
	m := r.Method
	if m == http.MethodGet {
		get(w, r)
		return
	}else if m == http.MethodPut {
		put(w, r)
		return
	}
	w.WriteHeader(http.StatusMethodNotAllowed)
}
func get(w http.ResponseWriter, r *http.Request) {
	// 收到 接口服务器的 请求
	// 提取 要获取的文件名
	name := strings.Split(r.URL.EscapedPath(), "/")[2]
	f, e := os.Open(storeDir + name)
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusNotFound)
		return
	}
	defer f.Close()
	// 真正读取,并发送
	io.Copy(w, f)
}
func put(w http.ResponseWriter, r *http.Request) {
	// 提取文件名
	fname := strings.Split(r.URL.EscapedPath(), "/")[2]
	log.Println(fname)
	// 创建文件
	f, e := os.Create(storeDir + fname)
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer f.Close()
	// 往文件写入数据
	io.Copy(f, r.Body)
}

func check(err error) {
	if err != nil{
		panic(err)
	}

}

func main() {
	mux :=http.NewServeMux()
	mux.HandleFunc("/up/", put)
	mux.HandleFunc("/download/", get)
	err := http.ListenAndServe(":8889", mux)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}

目前只开放了上传和下载接口,list,delete接口后续更新

你可能感兴趣的:(Go学习之旅之--实现一个小的本地存储)