普通网友 2018-10-23 19:38
浏览 8
已采纳

从结构转换/隐藏值

I have an application that creates a user at the database and returns his information (with struct). and I want to send the user model to the client (response of the web server), without password (or more information that I don't want the client will get). what the right way to do that? make a "UIUser" struct with the only fields that I want to send the client and convert the original model to this struct? or user interface?

and of course, if you can give me an example to solve this problem.

  • 写回答

2条回答 默认 最新

  • 啊啊啊小孔 2018-10-23 20:22
    关注

    Having view structs is probably a good idea in general, as you don't want to couple the API format to internal representation. Regardless, if you just wanna do this the lazy way and avoid serializing the password, you can always use the - json struct tag:

    package main
    
    import (
        "fmt"
        "encoding/json"
        "log"
    )
    
    type user struct {
        ID      int     `json:"id"`
        Name    string  `json:"name"`
        Pass    string  `json:"-"`
    }
    
    func main() {
        u := &user{123, "John", "supersecret"}
        b, err := json.Marshal(u)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(string(b))
    }
    

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!