Getting unexpected directory name in json output in Golang server

谁说我不能喝 提交于 2020-05-17 08:50:08

问题


I am new in Golang and I am trying to store image in the files on server and save its directory in MySQL Database. The code is running fine the DB is also storing the directory of the stored image correctly but the output json is showing the directory not correctly and I am not able to solve this. If also possible I want to give proper name to the saved file while creating and storing the image in the directory.I know should use jpeg or png but don't know how to set directory for these. The Directory has a parent folder profile-pic and child folder created from the mobile number I get form the POST Request where the image is stored. The Code is given below main.go

func main() {
    host, _ := os.Hostname()
    addrs, _ := net.LookupIP(host)
    for _, addr := range addrs {
        if ipv4 := addr.To4(); ipv4 != nil {
            fmt.Println("IPv4: ", ipv4)
        }
    }
    r := httprouter.New()
    uc := controller.NewUserController(getSession())
    r.GET("/", uc.Starter)
    r.POST("/create", uc.MobileCreate)
    http.ListenAndServe(":8080", r)
}

func getSession() *sql.DB {
    s, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/test")
    if err != nil {
        panic(err)
    }
    return s
}

controller.go

type UserController struct {
    session *sql.DB
}

func NewUserController(s *sql.DB) *UserController {
    return &UserController{s}
}
func (uc UserController) Starter(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
    dump, err := httputil.DumpRequest(r, true)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, `Your at homepage and Connection to db was success and check the terminal for dump diagnosis!`)
    fmt.Println("Request Dump:\n", string(dump))
}

func (uc UserController) MobileCreate(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    r.ParseMultipartForm(10 << 20)
    UserName := r.FormValue("name")
    EmailId := r.FormValue("email")
    PassWord := r.FormValue("password")
    MobileNumber := r.FormValue("mobile")
    i, _ := strconv.ParseInt(MobileNumber, 0, 64)
    AddRess := r.FormValue("address")
    ProfilePic, _, err := r.FormFile("profilePic")
    DirectoryName := "profile-pics" + "\\" + MobileNumber
    _ = DirectoryName + "\\" + "dp.png"
    if err != nil {
        fmt.Println("Error Retrieving the File")
        fmt.Println(err)
        return
    }
    defer ProfilePic.Close()

    _, err = os.Stat("test")
    if os.IsNotExist(err) {
        errDir := os.MkdirAll("profile-pics"+"\\"+MobileNumber, 0755)
        if errDir != nil {
            log.Fatal(err)
        }

    }

    tempFile, err := ioutil.TempFile("profile-pics"+"\\"+MobileNumber, "*.png")
    if err != nil {
        fmt.Println(err)
    }
    defer tempFile.Close()

    fileBytes, err := ioutil.ReadAll(ProfilePic)
    if err != nil {
        fmt.Println(err)
    }

    // write this byte array to our temporary file
    tempFile.Write(fileBytes)
    u := models.User{
        Name:       UserName,
        Email:      EmailId,
        Password:   PassWord,
        Mobile:     i,
        Address:    AddRess,
        ProfilePic: tempFile.Name(),
    }

    query, err := uc.session.Prepare("Insert loggedin SET name=?, email=?,pwd=?,number=?,address=?,profilepic=?")
    if err != nil {
        panic(err)
    }
    _, err = query.Exec(u.Name, u.Email, u.Password, u.Mobile, u.Address, u.ProfilePic)
    if err != nil {
        panic(err)
    }
    defer query.Close()

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated) // 201
    err = json.NewEncoder(w).Encode(u)
    if err != nil {
        fmt.Println(err)
    }
}

model/user.go

type User struct {
    Name       string `json:"name" `
    Email      string `json:"email" `
    Password   string `json:"password" `
    Mobile     int64  `json:"mobile" `
    Address    string `json:"address" `
    ProfilePic string `json: image`
}

The entry in database is correct

The json Output

"profile-pics\\9041111113\\103561439.png"

I tried naming the img to dp but the img was then saved in unsupported format

I want to remove double \\because i have to load this image in android app with picasso lib and it doesn't convert \\ to single \

 Picasso.get()
            .load(json output as string)
            .into(imageView)

I want to save the image in png only.

来源:https://stackoverflow.com/questions/61802648/getting-unexpected-directory-name-in-json-output-in-golang-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!