登录
首页 >  Golang >  Go问答

正确在Golang应用程序中生成UUID4的方法

来源:stackoverflow

时间:2024-03-25 12:24:35 310浏览 收藏

在 Go 应用程序中生成 UUID4 时,需要考虑以下要点: * 将 UUID 字段声明为 string 类型是合适的,符合最佳实践。 * 在使用 nulltime、nullint64 和 nullstring 等自定义数据类型时,确保实现 MarshalJSON 和 UnmarshalJSON 方法,并使用非指针接收器或在结构中设置字段指针,以避免 marshaljson 不起作用的问题。

问题内容

我是 golang 的新用户,需要一些帮助!我有几个问题。

postgresql 数据库中,我有一个名为 surveys 的表。

create table surveys(
  survey_id uuid primary key not null default uuid_generate_v4(),
  survey_name varchar not null,
  survey_description text,
  start_period timestamp,
  end_period timestamp
);

如您所见,survey_id 列是 primary key,其类型是 uuid4

golang 应用程序中,我为此表创建这样的 struct

type survey struct {
    id string `json:"survey_id"`
    name string `json:"survey_name"`
    description utils.nullstring `json:"survey_description"`
    startperiod utils.nulltime `json:"start_period"`
    endperiod utils.nulltime `json:"end_period"`
}

如您所见,id 字段的类型为 string。这是对的吗?我不确定这是否是最佳实践。

我的第二个问题是关于通过 id 向特定调查发出 get 请求时出现的奇怪结果。

例如,当我提出这样的请求时:

http://localhost:8000/api/survey/0cf1cf18-d5fd-474e-a8be-754fbdc89720

作为回应,我有这个:

{
    "survey_id": "0cf1cf18-d5fd-474e-a8be-754fbdc89720",
    "survey_name": "name",
    "survey_description": {
        "string": "description",
        "valid": true
    },
    "start_period": {
        "time": "2019-01-01t00:00:00z",
        "valid": false
    },
    "end_period": {
        "time": "0001-01-01t00:00:00z",
        "valid": false
    }
}

您可以看到最后 3 个字段有问题:survey_descriptionstart_periodend_period。我想在一行中查看键和值。例如如下:

{
    "survey_id": "0cf1cf18-d5fd-474e-a8be-754fbdc89720",
    "survey_name": "name",
    "survey_description": "description",
    "start_period": "2019-01-01 00:00:00",
    "end_period": null
}

我的代码到底在哪里出错了?

utils.go:

package utils

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "github.com/lib/pq"
    "time"
)

// nulltime is an alias for pq.nulltime data type.
type nulltime struct {
    pq.nulltime
}

// marshaljson for nulltime.
func (nt *nulltime) marshaljson() ([]byte, error) {
    if !nt.valid {
        return []byte("null"), nil
    }
    val := fmt.sprintf("\"%s\"", nt.time.format(time.rfc3339))
    return []byte(val), nil
}

// unmarshaljson for nulltime.
func (nt *nulltime) unmarshaljson(b []byte) error {
    err := json.unmarshal(b, &nt.time)
    nt.valid = err == nil
    return err
}

// nullint64 is an alias for sql.nullint64 data type.
type nullint64 struct {
    sql.nullint64
}

// marshaljson for nullint64.
func (ni *nullint64) marshaljson() ([]byte, error) {
    if !ni.valid {
        return []byte("null"), nil
    }
    return json.marshal(ni.int64)
}

// unmarshaljson for nullint64.
func (ni *nullint64) unmarshaljson(b []byte) error {
    err := json.unmarshal(b, &ni.int64)
    ni.valid = err == nil
    return err
}

// nullstring is an alias for sql.nullstring data type.
type nullstring struct {
    sql.nullstring
}

// marshaljson for nullstring.
func (ns *nullstring) marshaljson() ([]byte, error) {
    if !ns.valid {
        return []byte("null"), nil
    }
    return json.marshal(ns.string)
}

// unmarshaljson for nullstring.
func (ns *nullstring) unmarshaljson(b []byte) error {
    err := json.unmarshal(b, &ns.string)
    ns.valid = err == nil
    return err
}

routes.go:

router.handlefunc("/api/survey/{survey_id:[a-fa-f0-9]{8}-[a-fa-f0-9]{4}-4[a-fa-f0-9]{3}-[8|9|aa|bb][a-fa-f0-9]{3}-[a-fa-f0-9]{12}}", controllers.getsurvey).methods("get")

controllers/survey.go:

var GetSurvey = func(responseWriter http.ResponseWriter, request *http.Request) {
    // Initialize variables.
    survey := models.Survey{}
    var err error

    vars := mux.Vars(request)

    // Execute SQL statement.
    err = database.DB.QueryRow("SELECT * FROM surveys WHERE survey_id = $1;", vars["survey_id"]).Scan(&survey.ID, &survey.Name, &survey.Description, &survey.StartPeriod, &survey.EndPeriod)

    // Shape the response depending on the result of the previous command.
    if err != nil {
        log.Println(err)
        switch err {
        case sql.ErrNoRows:
            utils.ResponseWithError(responseWriter, http.StatusNotFound, "The entry not found.")
        default:
            utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
        }
        return
    }
    utils.Response(responseWriter, http.StatusOK, survey)
}

解决方案


嗯,终于找到结果了。

我更改了表的结构:

type survey struct {
    id string `json:"survey_id"`
    name string `json:"survey_name"`
    description *string `json:"survey_description", sql:"index"`
    startperiod *time.time `json:"start_period", sql:"index"`
    endperiod *time.time `json:"end_period", sql:"index"`
}

我没有发现使用 string 作为 uuid 存在任何问题。

至于 marshaljson 不起作用,我想我知道发生了什么事。您的 null 类型不实现 marshaljson,仅实现指向它们的指针。解决方法是更改​​函数以使用非指针接收器,或者在结构中设置字段指针。

func (ns *NullString) MarshalJSON() ([]byte, error)

如果您确实使它们成为指针,那么您可以像这样保留它们,因为它们可以为空。

本篇关于《正确在Golang应用程序中生成UUID4的方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>