Logo
31 Oct 2017 | 1 min. (160 words)

golang进阶(五)——restful开发的json处理

前言

restful开发时,对象转json,json转对象是非常频繁的操作,怎么样才能少些重复的代码呢,以这个为目的开启这篇文章

所有代码放在github上

简化数据结构

每次需要返回的数据有code,msg,data这些字段,每个类型都加这些字段太繁复了,这里有interface的方式,去代替任意类型,然后使用的时候data字段与其他类型任意的组合

package model

type Resp struct {
	Code string      `json:"code"`
	Msg  string      `json:"msg,omitempty"`
	Data interface{} `json:"data,omitempty"`
}

type User struct {
	Username string `json:"username"`
	Password string `json:"password,omitempty"`
}

json和http请求结合起来

对golang自带的json处理包装,使之可以直接从http请求中读出对象,把对象以json格式输出到响应中

package tools

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// MarshalJson 把对象以json格式放到response中
func MarshalJson(w http.ResponseWriter, v interface{}) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	fmt.Fprint(w, string(data))
	return nil
}

// UnMarshalJson 从request中取出对象
func UnMarshalJson(req *http.Request, v interface{}) error {
	result, err := ioutil.ReadAll(req.Body)
	if err != nil {
		return err
	}
	json.Unmarshal([]byte(bytes.NewBuffer(result).String()), v)
	return nil
}

调用

经过以上的处理,调用变得相当容易,不需要再做更多的重复编码,代码可读性上大大提高

func UserLoginndler(w http.ResponseWriter, r *http.Request) {
	user := &model.User{}
	tools.UnMarshalJson(r, user)
	resp := &model.Resp{Code: "1001", Msg: "账号或者密码错误"}
	if user.Username == "sweetop" && user.Password == "123456" {
		resp = &model.Resp{Code: "0", Msg: "success"}
	}
	tools.MarshalJson(w, resp)
}

api/user/login

func UserListHandler(w http.ResponseWriter, r *http.Request) {
	resp := &model.Resp{Code: "0", Msg: "success"}
	users := make([]model.User, 0)
	resp.Data = append(users, model.User{Username: "sweetop"})
	tools.MarshalJson(w, resp)
}

api/user/list

golang

golang进阶(六)——restful开发优雅处理error

golang的error处理一直被人诟病,其实通过设计模式可以很好的处理error,这里就以restful开发为例讲下error优雅的处理…

golang进阶(四)——路由mux的最佳实践

golang的自带的路由已经做到够好了,但是还是有一定的改进空间…

© 2009-2017 lastsweetop.com 版权所有 粤ICP备15102984号
Menu
  • 前言
  • 简化数据结构
  • json和http请求结合起来
  • 调用