douquanzhan0315 2019-03-09 22:20
浏览 151
已采纳

如何使用golang或go提交表单后在json中正确获取消息

How to properly get message in json after form submision using golang. Am just trying golang today for the first time.

Here is what am trying to achieve with golang:

In php for instance I can echo/print a json message after user submmitted a form and can then access it from the front end

Eg.

  if($everything == 'ok'){
 $messages = [
      'message' => 'User Registered successfully'
    ];
   echo json_encode($messages);
exit();
  }

Please How do I do this with golang.

The code below works fine by inserting records to database. Upon a successful insert, it display a success message in the code below and everything is working fine.

res.Write([]byte("User Registered successfully!" +username))

Here is my qusetion: How do I get json response of the successful message so that I can access it from my front end just like in php code above.

I have tried

messageJson := `{"message": "User Registered successfully"}`
jsonresult_send := json.Marshal(messageJson)

return jsonresult_send

But it displays error too many argument to return

Here is the entire code



package main

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

import "net/http"
import "fmt"
import "encoding/json"

var db *sql.DB
var err error



type MessageInfo struct {
  Message string
}



func signupPage(res http.ResponseWriter, req *http.Request) {
    if req.Method != "POST" {
        http.ServeFile(res, req, "signupjson.html")
        return
    }



        username := req.FormValue("username")
    password := req.FormValue("password")



    var user string
         err := db.QueryRow("SELECT username FROM users WHERE username=?", username).Scan(&user)


    switch {
    case err == sql.ErrNoRows:
        _, err = db.Exec("INSERT INTO users(username, password) VALUES(?, ?)", username, password)
        if err != nil {
            http.Error(res, "insert error, unable to create your account.", 500)
            return
        }

res.Write([]byte("User Registered successfully!" +username))

// get json response message

messageJson := `{"message": "User Registered successfully"}`
jsonresult_send := json.Marshal(messageJson)

return jsonresult_send

        return
    default:
        http.Redirect(res, req, "/", 301)
    }
}



func homePage(res http.ResponseWriter, req *http.Request) {
    http.ServeFile(res, req, "index.html")
}

func main() {
    db, err = sql.Open("mysql", "root:@/golang44")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    http.HandleFunc("/signupjson", signupPage)
    http.HandleFunc("/", homePage)
        fmt.Println("Listening on 127.0.0.1:8088")
    http.ListenAndServe(":8088", nil)
}
  • 写回答

1条回答 默认 最新

  • duanke3985 2019-03-10 00:54
    关注

    If I understood correctly, what you need is this:

    func GetPeople(w http.ResponseWriter, r *http.Request) {
        json.NewEncoder(w).Encode(people)
    }
    

    In your case, you could solve it in two ways:

    1. With a struct
    type Info struct {
        Message string `json:"message"`
    }
    
    func MyHandler(w http.ResponseWriter, r *http.Request) {
        ... Some processing here ...
    
        info := Info{Message: "User Registered successfully"}
        json.NewEncoder(w).Encode(info)
    }
    
    1. With a map
    func MyHandler(w http.ResponseWriter, r *http.Request) {
        ... Some processing here ...
    
        info := map[string]string{"message": "User Registered successfully"}
        json.NewEncoder(w).Encode(info)
    }
    

    If anyone can test to look for some syntax error I appreciate it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致