Below is my main.go file to upload images.
Here using this go file am building a docker image.
docker build is successful.
On accessing the minikube service url, get options to upload, list and delete files.
But once clicked on Upload file, get site cannot be reached.
var baseDirectory string
var ipaddress string
func main() {
baseDirectory = "/usr/local/go/" // provide the base directory path where the files will be kept
ipaddress = "localhost" // provide the ip address of the webserver
http.HandleFunc("/", homePage)
http.HandleFunc("/uploadfile", uploadFile)
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
err := http.ListenAndServe(":80", nil)
if err != nil {
fmt.Println("Error occurred ", err)
}
}
func homePage(w http.ResponseWriter, req *http.Request) {
var options [1]string
options[0] = "</br><a href = \"http://" + ipaddress + ":80/uploadfile\">Click to upload file</a></br>"
w.Header().Set("CONTENT-TYPE", "text/html; charset=UTF-8")
fmt.Fprintf(w, "<h1>%s</h1>, <div>%s</div>", "Home Page
", options)
}
func uploadFile(w http.ResponseWriter, req *http.Request) {
//var s string
if req.Method == http.MethodPost {
f, handler, err := req.FormFile("usrfile")
if err != nil {
log.Println(err)
http.Error(w, "Error uploading file", http.StatusInternalServerError)
return
}
defer f.Close()
filename := handler.Filename
fmt.Println(filename)
bs, err := ioutil.ReadAll(f)
if err != nil {
log.Println(err)
http.Error(w, "Error reading file", http.StatusInternalServerError)
return
}
fmt.Println(bs)
err1 := ioutil.WriteFile(baseDirectory+filename, bs, 0644)
if err != nil {
log.Fatal(err1)
}
fmt.Println("Success!")
}
w.Header().Set("CONTENT-TYPE", "text/html; charset=UTF-8")
fmt.Fprintf(w, `<form action="/uploadfile" method="post" enctype="multipart/form-data">
Upload a file<br>
<input type="file" name="usrfile"><br>
<input type="submit">
</form>
<br>
<br>`)
}