Exemple #1
0
func (a *server) handleSingleSite(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	id := xmux.Param(ctx, "id")
	err := json.NewEncoder(w).Encode(a.sites.GetSite(id))
	if err != nil {
		log.Println(err)
	}
}
Exemple #2
0
func getNoteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	noteID := xmux.Param(ctx, "id")
	db := ctx.Value(ctxKeyDB).(*DB)
	note, err := getNote(db, noteID)
	if err != nil {
		if err == sql.ErrNoRows {
			log.Printf("getNoteHandler: %s", err)
			w.Header().Set("Content-type", "application/json")
			w.WriteHeader(http.StatusNotFound)
			res := MessageResponse{Data: StatusMessage{Message: "not found"}}
			json.NewEncoder(w).Encode(res)
			return
		}
		log.Printf("getNoteHandler: %s", err)
		w.Header().Set("Content-type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		res := MessageResponse{Data: StatusMessage{Message: "error"}}
		json.NewEncoder(w).Encode(res)
		return
	}
	w.Header().Set("Content-type", "application/json")
	res := NoteResponse{Data: note}
	json.NewEncoder(w).Encode(res)
	return
}
Exemple #3
0
func updateNoteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var noteRequest NoteRequest
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&noteRequest)
	if err != nil {
		log.Printf("updateNoteHandler: %s", err)
		w.Header().Set("Content-type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		res := MessageResponse{Data: StatusMessage{Message: "error"}}
		json.NewEncoder(w).Encode(res)
		return
	}

	noteID, _ := strconv.Atoi(xmux.Param(ctx, "id"))
	noteRequest.Data.ID = noteID
	db := ctx.Value(ctxKeyDB).(*DB)
	err = updateNote(db, noteRequest.Data)
	if err != nil {
		log.Printf("getNoteHandler: %s", err)
		w.Header().Set("Content-type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		res := MessageResponse{Data: StatusMessage{Message: "error"}}
		json.NewEncoder(w).Encode(res)
		return
	}
	w.Header().Set("Content-type", "application/json")
	res := MessageResponse{Data: StatusMessage{Message: "updated"}}
	json.NewEncoder(w).Encode(res)
	return
}
func ExampleMux_NewGroup() {
	mux := xmux.New()

	api := mux.NewGroup("/api")

	api.GET("/users/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "GET /api/users/%s", xmux.Param(ctx, "name"))
	}))

	api.POST("/users/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "POST /api/users/%s", xmux.Param(ctx, "name"))
	}))

	if err := http.ListenAndServe(":8080", xhandler.New(context.Background(), mux)); err != nil {
		log.Fatal(err)
	}
}
Exemple #5
0
func (a *server) handleDownload(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	hash := strings.ToUpper(xmux.Param(ctx, "hash"))
	url := fmt.Sprintf(
		"%s/torrent/%s.torrent",
		a.torcacheURL,
		url.QueryEscape(hash),
	)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	req.Header.Set("User-Agent", "Magopie Server")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer res.Body.Close()

	// Ensure download directory exists
	// TODO should this be done every request?
	err = a.fs.MkdirAll(a.downloadDir, 0755)
	if err != nil {
		log.Print("Error making download dir", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Create file to write torrent
	// TODO create with .part or something then move when done
	path := filepath.Join(a.downloadDir, hash+".torrent")
	file, err := a.fs.Create(path)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Copy file contents from torcache response to os file
	_, err = io.Copy(file, res.Body)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusCreated)
}
Exemple #6
0
func deleteNoteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	noteID := xmux.Param(ctx, "id")
	db := ctx.Value(ctxKeyDB).(*DB)
	err := deleteNote(db, noteID)
	if err != nil {
		log.Printf("deleteNoteHandler: %s", err)
		w.Header().Set("Content-type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		res := MessageResponse{Data: StatusMessage{Message: "error"}}
		json.NewEncoder(w).Encode(res)
		return
	}
	w.Header().Set("Content-type", "application/json")
	res := MessageResponse{Data: StatusMessage{Message: "deleted"}}
	json.NewEncoder(w).Encode(res)
	return
}
Exemple #7
0
func ExampleMux() {
	c := xhandler.Chain{}

	// Append a context-aware middleware handler
	c.UseC(xhandler.CloseHandler)

	// Another context-aware middleware handler
	c.UseC(xhandler.TimeoutHandler(2 * time.Second))

	mux := xmux.New()

	// Use c.Handler to terminate the chain with your final handler
	mux.GET("/welcome/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome %s!", xmux.Param(ctx, "name"))
	}))

	if err := http.ListenAndServe(":8080", c.Handler(mux)); err != nil {
		log.Fatal(err)
	}
}
Exemple #8
0
func (a *server) handleDownload(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	hash := strings.ToUpper(xmux.Param(ctx, "hash"))
	url := fmt.Sprintf(
		"%s/torrent/%s.torrent",
		a.torcacheURL,
		url.QueryEscape(hash),
	)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	req.Header.Set("User-Agent", "Magopie Server")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer res.Body.Close()

	// Ensure download directory exists
	// TODO should this be done every request?
	err = a.fs.MkdirAll(a.downloadDir, 0755)
	if err != nil {
		log.Print("Error making download dir", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// Create temp .part file to write torrent contents from the response Body
	// then move .part file to .torrent. We do this so other services don't see
	// the .torrent file while we're still writing it and moving it is an atomic
	// operation.
	tempPath := filepath.Join(a.downloadDir, hash+".part")
	finalPath := filepath.Join(a.downloadDir, hash+".torrent")
	file, err := a.fs.Create(tempPath)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	_, err = io.Copy(file, res.Body)
	if err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	if err := a.fs.Rename(tempPath, finalPath); err != nil {
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusCreated)
}
Exemple #9
0
func unoconvHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	l := xlog.FromContext(ctx)

	//The whole request body is parsed and up to a total of 34MB bytes of its file parts are stored in memory,
	//with the remainder stored on disk in temporary files.
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("file")
	if err != nil {
		l.Error(err)
		return
	}
	defer file.Close()

	//add the filename to access log
	l.SetField("filename", handler.Filename)

	//create a temporary file and copy the file from the form to it
	tempfile, err := ioutil.TempFile(os.TempDir(), "unoconv-api")
	if err != nil {
		l.Error(err)
		return
	}

	switch filepath.Ext(handler.Filename) {
	case ".txt":
		//read the files content
		data, err := ioutil.ReadAll(file)
		if err != nil {
			l.Error(err)
			return
		}

		//try to convert the textfile (data) to utf-8 and write it to tempfile
		charset, err := toUTF8(data, tempfile)
		l.SetField("charset", charset)
		l.SetField("convertedToUTF8", true)
		if err != nil {
			//Could not convert to utf-8, write the original data to tempfile
			l.Error(err)
			l.SetField("convertedToUTF8", false)
			io.Copy(tempfile, bytes.NewBuffer(data))
		}
	default:
		io.Copy(tempfile, file)
	}

	tempfile.Close()

	//append the file extension to the temporary file's name
	filename := tempfile.Name() + filepath.Ext(handler.Filename)
	os.Rename(tempfile.Name(), filename)
	defer os.Remove(filename)

	//Run unoconv to convert the file
	//unoconv's stdout is plugged directly to the httpResponseWriter
	err = uno.convert(filename, xmux.Param(ctx, "filetype"), w)
	if err != nil {
		l.Error(err)
		return
	}
}