在golang中,编写JSON和MySQL查询字符串的良好格式是什么?

huangapple go评论85阅读模式
英文:

In golang, what is nice format to write JSON and MySQL query string?

问题

在golang源代码中,阅读非常长的JSON字符串或数据库查询语句确实很困难。

JSON示例:

"{\"task\":\"send_sms\",\"t_id\":988110,\"req\":{\"node\":1,\"msg_id\":987654321,\"m_num\":\"+61433092888\",\"p_num\":\"Private\",\"msg\":\"Hello world.\"}}"

数据库查询示例:

dbQuery = fmt.Sprintf("INSERT INTO `ms_message` (`task_id`, `panel_phone_num` ,`user_mobile_num`,`message_content`,`receiver_node_id`,`modem_index`,`generate_datetime` ) SELECT * FROM (SELECT %d, \"%s\", \"%s\", \"%s\", %d,%d,\"%s\") AS tmp WHERE NOT EXISTS ( SELECT * FROM `ms_message` WHERE `receiver_node_id` = %d AND `task_id` = %d ) LIMIT 1", taskId, panelNumber, mobileNumber, messageContent, nodeId, modemId, dateTime, nodeId, taskId)

有什么好的方法可以使上述字符串更易于阅读?

英文:

It is really hard to read an extremely long string of JSON or DB query in golang source code.

JSON Example:

"{\"task\":\"send_sms\",\"t_id\":988110,\"req\":{\"node\":1,\"msg_id\":987654321,\"m_num\":\"+61433092888\",\"p_num\":\"Private\",\"msg\":\"Hello world.\"}}      "

DB Query Example:

dbQuery = fmt.Sprintf("INSERT INTO `ms_message` (`task_id`, `panel_phone_num` ,`user_mobile_num`,`message_content`,`receiver_node_id`,`modem_index`,`generate_datetime` ) SELECT * FROM (SELECT %d, \"%s\", \"%s\", \"%s\", %d,%d,\"%s\") AS tmp WHERE NOT EXISTS ( SELECT * FROM `ms_message` WHERE `receiver_node_id` = %d AND `task_id` = %d ) LIMIT 1", taskId, panelNumber, mobileNumber, messageContent, nodeId, modemId, dateTime, nodeId, taskId)

What way is nice to make above strings looks reader friendly?

答案1

得分: 1

你可以使用反引号来编写多行的字符串文字,例如:

json := `
{
    "hello": "world",
    "foo": "bar"
}`

在你的SQL示例中使用反引号可能会有问题...

英文:

You can use backticks to write a multiline string literal, like so:

json := `
{
	"hello": "world",
	"foo": "bar"
}`

https://play.golang.org/p/bU5q6tx8Jx

The backticks in your SQL example might be problematic, though...

huangapple
  • 本文由 发表于 2016年3月3日 07:09:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/35760047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定