mirror of
https://github.com/maputnik/editor.git
synced 2025-12-06 06:10:00 +00:00
Write and read file directly
This commit is contained in:
32
api.go
32
api.go
@@ -1,28 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func StyleFileAccessor(filename string) styleFileAccessor {
|
||||
file, err := os.OpenFile(filename, os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
log.Fatalf("Can not access style file: %s", err.Error())
|
||||
}
|
||||
|
||||
return styleFileAccessor{file, styleId(file)}
|
||||
return styleFileAccessor{filename, styleId(filename)}
|
||||
}
|
||||
|
||||
func styleId(file *os.File) string {
|
||||
raw, err := ioutil.ReadAll(file)
|
||||
func styleId(filename string) string {
|
||||
raw, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
log.Panicln(err)
|
||||
}
|
||||
@@ -45,8 +39,8 @@ type styleSpec struct {
|
||||
|
||||
// Allows access to a single style file
|
||||
type styleFileAccessor struct {
|
||||
file *os.File
|
||||
id string
|
||||
filename string
|
||||
id string
|
||||
}
|
||||
|
||||
func (fa styleFileAccessor) ListFiles(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -62,10 +56,12 @@ func (fa styleFileAccessor) ReadFile(w http.ResponseWriter, r *http.Request) {
|
||||
//TODO: Choose right file
|
||||
// right now we just return the single file we know of
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fa.file.Seek(0, 0)
|
||||
if _, err := io.Copy(w, fa.file); err != nil {
|
||||
log.Fatalf("Can not copy from file to request: %s", err.Error())
|
||||
|
||||
raw, err := ioutil.ReadFile(fa.filename)
|
||||
if err != nil {
|
||||
log.Panicln(err)
|
||||
}
|
||||
w.Write(raw)
|
||||
}
|
||||
|
||||
func (fa styleFileAccessor) SaveFile(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -75,7 +71,11 @@ func (fa styleFileAccessor) SaveFile(w http.ResponseWriter, r *http.Request) {
|
||||
//TODO: Save to right file
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if _, err := io.Copy(fa.file, r.Body); err != nil {
|
||||
body, _ := ioutil.ReadAll(r.Body)
|
||||
var out bytes.Buffer
|
||||
json.Indent(&out, body, "", " ")
|
||||
|
||||
if err := ioutil.WriteFile(fa.filename, out.Bytes(), 0666); err != nil {
|
||||
log.Fatalf("Can not copy from request to file: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user