分布式是写出来的(一)

分布式对象存储笔记

实现一个单机版本的对象存储

package main

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


func Handler(w http.ResponseWriter, r *http.Request) {
	m := r.Method
	if m == http.MethodPut {
		put(w, r)
		return
	}
	if m == http.MethodGet {
		get(w, r)
		return
	}
	w.WriteHeader(http.StatusMethodNotAllowed)
}

func get(w http.ResponseWriter, r *http.Request) {
	f, e := os.Open("C:/Users/HodgeKou/go/src/distribute_file_system/chapter1" + "/object/" + strings.Split(r.URL.EscapedPath(), "/") [2])
	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) {
	f, e := os.Create("C:/Users/HodgeKou/go/src/distribute_file_system/chapter1" + "/object/" + strings.Split(r.URL.EscapedPath(), "/") [2])
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer f.Close()
	io.Copy(f, r.Body)
}


func main() {
	http.HandleFunc("/object/", object.Handler)
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

Test

Test put数据

C:\Users\HodgeKou\go\src\distribute_file_system>curl -v 127.0.0.1:8080/object/1234.txt -XPUT -d "add test"
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> PUT /objects/123.txt HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 4
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 4 out of 4 bytes
< HTTP/1.1 405 Method Not Allowed
< Date: Thu, 09 Apr 2020 06:18:51 GMT
< Content-Length: 0
<
* Connection #0 to host 127.0.0.1 left intact

Test get数据

C:\Users\HodgeKou\go\src\distribute_file_system>curl -v 127.0.0.1:8080/object/1234.txt
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> GET /object/1234.txt HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Thu, 09 Apr 2020 07:20:36 GMT
< Content-Type: text/plain; charset=utf-8
< Transfer-Encoding: chunked
<
add test* Connection #0 to host 127.0.0.1 left intact
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值