Skip to content

Commit

Permalink
#1 单机版对象存储
Browse files Browse the repository at this point in the history
  • Loading branch information
pojiang20 committed Dec 15, 2022
1 parent 5a26253 commit b79ba86
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
# distribute-object-storage
Simple distributed object storage implemented by go

### 1 单机版对象存储
mkdir /tmp/objects

`LISTEN_ADDRESS=:12345 STORAGE_ROOT=/tmp go run server.go`

存对象`curl -v 127.0.0.1:12345/objects/test -XPUT -d "this is a test object"`
取对象`curl -v 127.0.0.1:12345/objects/test`
15 changes: 15 additions & 0 deletions objects/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package objects

import "net/http"

func Handler(w http.ResponseWriter, r *http.Request) {
m := r.Method

if m == http.MethodPut {
put(w, r)
} else if m == http.MethodGet {
get(w, r)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
37 changes: 37 additions & 0 deletions objects/restful_apis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package objects

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

const (
STORAGE_ROOT = "STORAGE_ROOT"
)

func put(w http.ResponseWriter, r *http.Request) {
f, err := os.Create(os.Getenv(STORAGE_ROOT) + "/objects/" +
strings.Split(r.URL.EscapedPath(), "/")[2])
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(f, r.Body)
}

func get(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(os.Getenv(STORAGE_ROOT) + "/objects/" +
strings.Split(r.URL.EscapedPath(), "/")[2])
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(w, f)
}
2 changes: 2 additions & 0 deletions server.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
LISTEN_ADDRESS=:12345
STORAGE_ROOT=/tmp/storage
18 changes: 18 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

import (
"github.com/pojiang20/distribute-object-storage/objects"
"log"
"net/http"
"os"
)

const (
listenAddress = "LISTEN_ADDRESS"
ObjectsPattern = "/objects/"
)

func main() {
http.HandleFunc(ObjectsPattern, objects.Handler)
log.Print(http.ListenAndServe(os.Getenv(listenAddress), nil))
}

0 comments on commit b79ba86

Please sign in to comment.