分布式对象存储笔记
实现一个单机版本的对象存储
package mainimport ( "io" "log" "net/http" "os" "strings"
) func Handler ( w http. ResponseWriter, r * http. Request) { m : = r. Methodif 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: *
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: *