Created
July 9, 2019 02:44
-
-
Save yurisasuke/42eaeb9932cface43cac226a9d4ae30c to your computer and use it in GitHub Desktop.
Golang absolute image url...when compiled
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 ( | |
"io" | |
"path" | |
"encoding/json" | |
"log" | |
"net/http" | |
"os" | |
"github.com/julienschmidt/httprouter" | |
"github.com/satori/go.uuid" | |
) | |
var IMAGE_PATH = "/Users/keithwacira/go/src/resize/images/" | |
func main() { | |
router := httprouter.New() | |
router.POST("/api/v1/employee/update/image", UpdateEmployeePicture) | |
http.ListenAndServe("0.0.0.0:3000", router) | |
} | |
func UpdateEmployeePicture(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { | |
imageName, err := FileUpload(r) | |
//here we call the function we made to get the image and save it | |
if err != nil { | |
print(err) | |
//checking whether any error occurred retrieving image | |
} | |
employerId := r.FormValue("employeeId") | |
///var payloadRes model.Employee | |
log.Println(employerId) | |
log.Println(imageName) | |
employee := map[string]interface{}{ | |
"image_url": imageName, | |
"employeeId": employerId, | |
} | |
///_ = h.database.Model(&model.Employee{}).Where("employee_id = ?", employerId). | |
//// Updates(model.Employee{ImageURL: imageName}).Scan(&payloadRes) | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(http.StatusOK) | |
_ = json.NewEncoder(w).Encode(employee) | |
} | |
func FileUpload(r *http.Request) (string, error) { | |
//this function returns the filename(to save in database) of the saved file or an error if it occurs | |
_ = r.ParseMultipartForm(32 << 20) | |
//ParseMultipartForm parses a request body as multipart/form-data | |
file, fh, err := r.FormFile("myFile") //retrieve the file from form data | |
defer file.Close() //close the file when we finish | |
u2, err := uuid.NewV4() | |
if err != nil { | |
return "", err | |
} | |
v := u2.String() | |
var file_name = v + path.Ext(fh.Filename) | |
var errors error | |
if err != nil { | |
errors = err | |
} | |
storage := IMAGE_PATH + file_name | |
log.Println(storage) | |
//this is path which we want to store the file | |
f, err := os.OpenFile(storage, os.O_WRONLY|os.O_CREATE, 0666) | |
if err != nil { | |
errors = err | |
} | |
defer f.Close() | |
_, _ = io.Copy(f, file) | |
//here we save our file to our path | |
return file_name, errors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment