Last active
May 27, 2020 16:37
-
-
Save jaedsadadotme/e49a36f86b5b152e2e8fcba5076bc573 to your computer and use it in GitHub Desktop.
uploadfile local ด้วย golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
// simple | |
func uploadFile(w http.ResponseWriter, r *http.Request) { | |
fmt.Printf("====Upload File ===") | |
file, _, err := r.FormFile("file") | |
if err != nil { | |
fmt.Println("Error ", err) | |
return | |
} | |
defer file.Close() | |
tempFile, err := ioutil.TempFile("tmp-file", "upload-*.png") | |
if err != nil { | |
log.Println("error 1", err) | |
return | |
} | |
defer file.Close() | |
fileBytes, err := ioutil.ReadAll(file) | |
if err != nil { | |
log.Println("error 2", err) | |
return | |
} | |
tempFile.Write(fileBytes) | |
data := map[string]string{ | |
"msg": "Hello Golang", | |
"files": tempFile.Name(), | |
} | |
json.NewEncoder(w).Encode(&data) | |
} | |
func getFile(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
file, err := ioutil.ReadFile("images/" + vars["file"]) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusNotFound) | |
return | |
} | |
w.Header().Set("Content-type", "image/png") | |
w.Write(file) | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
data := map[string]string{ | |
"msg": "Hello Golang", | |
} | |
json.NewEncoder(w).Encode(&data) | |
} | |
func setupRoutes() { | |
r := mux.NewRouter() | |
r.HandleFunc("/", hello).Methods(http.MethodGet) | |
r.HandleFunc("/getfile/{file}", getFile).Methods(http.MethodGet) | |
r.HandleFunc("/upload/", uploadFile).Methods(http.MethodPost) | |
log.Println("listen port :1234") | |
http.ListenAndServe(":1234", r) | |
} | |
func main() { | |
setupRoutes() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment