golang api 返回值定义和读取(json文件)

Golang · Fecmall · 于 5年前 发布 · 2309 次阅读

对于go api返回的状态,可以在一个json文件中定义,通过编号得到错误的内容

通过语言得到相应的对应值

map_data.json

{
  "maps": [
    {
      "map_name": "error_codes_en",
      "entries": {
        "0": "Success",
        "-1000": "Unexpected system error occurred. Please try again later",
        "-1001": "Bad Request",
        "-1002": "Your requested data do not exist",
        "-1003": "This show time is no longer available",
        "-1004": "The layout temporarily not available",
        "-1005": "Similar order has been requested before",
        "-1006": "Failed to book seat(s)",
        "-1007": "Booking not found",
        "-1008": "Ticket not available",
        "-1009": "Invalid showtime",
        "-1010": "Unable to process checkout",
        "-1011": "Connection to XXI timed out",
        "-1012": "User not found",
        "-1013": "XXI ticket transaction has been canceled",
        "-1014": "Active Tickets not available",
        "-1016": "Unknown ticket filter",
        "-1017": "XXI checkout request is duplicated",
        "-1018": "Order not found",
        "-1019": "Order has been expired",
        "-1021": "Order failed. Seat already taken.",
        "-1022": "Not enough balance, please top-up",
        "-1023": "Promo not valid or already expired",
        "-1100": "Phone Number already registered",
        "-1101": "Incorrect phone number or password",
        "-1112": "Payment cannot be processed",
        "-1113": "Cannot process order",
        "-1120": "Old password did not match",
        "-1121": "New password cannot be the same as before",
        "-1122": "Venue not found",
        "-1123": "Movie not found",
        "-1124": "Unable to favorites more than 10 items",
        "-1130": "Verification failed because OTP code not found or already verified",
        "-1131": "Verification failed because wrong OTP code",
        "-1132": "Verification failed because too many wrong OTP code. Please request new OTP code.",
        "-1133": "This order is no longer available.",
        "-1134": "Concurrent verifications to the same number are not allowed. Please try again later.",
        "-1135": "Your DANA account is frozen. Please call our customer service to unfreeze your DANA account",
        "-1136": "No schedule available",
        "-1137": "Referral code is invalid",
        "-1138": "This device is already redeemed a code before",
        "-1139": "User has already redeem this voucher",
        "-1140": "Redeem voucher failed",
        "-1141": "Request promo failed",
        "-1142": "Create voucher failed",
        "-1143": "Insert into user relationship table failed",
        "-1144": "You may have been used this code or it is no longer valid anymore.",
        "-1145": "You can only redeem one voucher code from %s during promotion periode.",
        "-1146": "This promo code has already reached the maximum limit to be exchanges. Please try another code.",
        "-1201": "Due to high enthusiasm, we are now still processing all previous transactions. Please try again in a few minutes.",
        "-1202": "You can’t make any transactions at this show time due to it’s already reach the limit to purchase. Please try another show time.",
        "-1203": "You have reach maximum purchasing limit %d tickets per day.",
        "-1300": "Quota is out of room capacity.",
        "-1301": "Sale expired date can't be higher than event start date.",
        "-1302": "Event end date can't be lower than event start date."
      }
    },
    {
      "map_name": "error_codes_id",
      "entries": {
        "0": "Berhasil",
        "-1000": "Sistem sedang bermasalah. Silakan coba beberapa saat lagi",
        "-1001": "Server tidak dapat mengenali permintaan Anda",
        "-1002": "Data yang Anda minta tidak ditemukan",
        "-1003": "Jam tayang ini sudah tidak tersedia",
        "-1004": "Layout untuk sementara tidak tersedia",
        "-1005": "Pesanan serupa pernah dipesan sebelumnya",
        "-1006": "Gagal memesan kursi",
        "-1007": "Pemesanan tidak tersedia",
        "-1008": "Tiket tidak tersedia",
        "-1009": "Jadwal film tidak ditemukan",
        "-1010": "Tidak dapat memproses transaksi",
        "-1011": "Waktu koneksi ke XXI telah berakhir",
        "-1012": "User tidak ditemukan",
        "-1013": "Transaksi tiket XXI telah dibatalkan",
        "-1014": "Tidak ada tiket aktif saat ini",
        "-1016": "Filter tiket tidak dikenali",
        "-1017": "Terjadi duplikasi pemesanan di XXI.",
        "-1018": "Pesanan tidak ditemukan",
        "-1019": "Pesanan telah kadaluarsa",
        "-1021": "Pesanan tidak dapat diproses, kursi sudah terjual.",
        "-1022": "Saldo tidak cukup, silahkan isi ulang",
        "-1023": "Promo sudah tidak valid atau kadaluarsa",
        "-1100": "Nomor handphone sudah terdaftar",
        "-1101": "Nomor handphone atau password salah",
        "-1112": "Pembayaran tidak bisa diproses",
        "-1113": "Pesanan tidak dapat diproses",
        "-1120": "Password lama tidak sama",
        "-1121": "Password baru tidak boleh sama dengan sebelumnya",
        "-1122": "Lokasi tidak ditemukan",
        "-1123": "Film tidak ditemukan",
        "-1124": "Tidak dapat memfavoritkan lebih dari 10 item",
        "-1130": "Verifikasi gagal karena kode OTP tidak ditemukan atau sudah terverifikasi",
        "-1131": "Verifikasi gagal karena kode OTP salah",
        "-1132": "Verifikasi gagal karena terlalu banyak mencoba kode OTP. Harap meminta sms kode OTP baru",
        "-1133": "Pesanan ini sudah tidak tersedia",
        "-1134": "Verifikasi serentak ke nomor yang sama tidak diperbolehkan. Silakan coba lagi nanti",
        "-1135": "Akun DANA Anda tidak aktif. Hubungi layanan pelanggan kami untuk mengaktifkan kembali akun DANA Anda",
        "-1136": "Tidak ada jadwal yang tersedia",
        "-1137": "Kode referral tidak valid",
        "-1138": "Perangkat ini sudah menukarkan kode sebelumnya",
        "-1139": "User sudah melakukan redeem voucher sebelumnya",
        "-1140": "Redeem voucher gagal",
        "-1141": "Pengajuan promo gagal",
        "-1142": "Pembuatan voucher gagal",
        "-1143": "Memasukan data ke table user relationship gagal",
        "-1144": "Kode mungkin telah digunakan atau kode sudah tidak berlaku lagi.",
        "-1145": "Anda hanya dapat menukarkan satu kode voucher dari %s selama periode promo.",
        "-1146": "Kode promo ini sudah mencapai batas maksimum untuk ditukar. Silakan coba kode promo lainnya.",
        "-1201": "Karena tingginya transaksi di TIX ID, saat ini kami sedang memproses transaksi yang telah dilakukan oleh pengguna sebelumnya. Silakan kembali beberapa saat lagi.",
        "-1202": "Anda tidak dapat melakukan transaksi pada waktu tayang ini karena sudah mencapai batas pembelian tiket. Coba lagi pada waktu tayang lainnya.",
        "-1203": "Anda telah melebihi batas pembelian maksimum %d tiket per hari.",
        "-1300": "Kuota melebihi kapasitas ruangan.",
        "-1301": "Tanggal/jam Sale expired tidak boleh melebihi Event start.",
        "-1302": "Tanggal/jam Event end tidak boleh kurang dari Event start."
      }
    }
  ]
}

各个编号对应相应的信息

package main

import (
	"flag"
	"fmt"
	"os"
	"strconv"
	"time"
	"xxx/util"
)

var log = logging.MustGetLogger()
var appRelic newrelic.Application

func main() {

	// Must be initialized before backends
	err = util.InitializeMaps("./map_data.json")
	if err != nil {
		log.Fatal("error reading map_data.json: ", err.Error())
		return
	}

"xxx/util"包 maps.go

package util

import (
	"encoding/json"
	"io/ioutil"
	"strings"
	"xxx/logging"
)

var log = logging.MustGetLogger()
var maps = make(map[string](map[string]string))

const (
	M_ERROR_CODES_EN    = "error_codes_en"
	M_ERROR_CODES_ID    = "error_codes_id"
)

type Map struct {
	Name    string            `json:"map_name"`
	Entries map[string]string `json:"entries"`
}

type MapsDocument struct {
	Maps []Map `json:"maps"`
}

// Call this to cause the map data to be loaded from the specified file
// and placed into the private maps map
func InitializeMaps(fileName string) error {
	bytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Error("Error reading maps file ", err.Error())
		return err
	}
	log.Info("found map data file map_data.json")
	doc := MapsDocument{}
	if err := json.Unmarshal(bytes, &doc); err != nil {
		return err
	}
	for _, elem := range doc.Maps {
		log.Debug( "populating map ", elem.Name)
		maps[elem.Name] = elem.Entries
	}
	log.Info( "parsed map data file map_data.json")

	return nil
}

// Call this to get a specific map
// NOTE that the caller is then RESPONSIBLE for handling
// cases where the keys of interest are not present
// Preferably use MustGetString() or LookupFunc()
// Panics if the map of interest is not found
func MustGetMap(mapName string) map[string]string {
	m, ok := maps[mapName]
	if !ok {
		log.Error("missing map ", mapName)
		panic("missing map " + mapName)
	}
	return m
}


// Call this to get the value associated with a key in a given map
// Panics if either the map or key are not found
func MustGetString(mapName string, key string) string {
	m := MustGetMap(mapName)

	v, ok := m[key]
	if !ok {
		log.Error("missing key ", key," in map ", mapName)
		panic("missing key " + key + "in map " + mapName)
	}
	return v
}

type MappingFunc func(string) string

// Returns a function that can be used to retrieve keys from
// the specified map
// The returned function will panic if asked to retrieve from a map
// or a key that does not exist
func LookupFunc(mapName string) MappingFunc {

	return func(key string) string {
		m := MustGetMap(mapName)
		v, ok := m[key]
		if !ok {
			log.Error( "missing key ", key," in map ", mapName)
			panic("missing key " + key + " in map " + mapName)
		}
		return v
	}
}

// working the same as LookupFunc, but if the key is not found, it will override with another key
func LookupFuncWithDefaultKey(mapName string, defaultKey string) MappingFunc {

	return func(key string) string {
		m := MustGetMap(mapName)
		v, ok := m[key]
		if !ok {
			return LookupFunc(mapName)(defaultKey)
		}
		return v
	}
}

func LookupFuncIgnoreCase(mapName string) MappingFunc {

	return func(key string) string {
		m := MustGetMap(mapName)
		v, ok := m[strings.TrimSpace(strings.ToLower(key))]
		if !ok {
			log.Error( "missing key ", key," in map ", mapName)
			panic("missing key " + key + " in map " + mapName)
		}
		return v
	}
}

func LookupFuncIgnoreCaseNoPanic(mapName string) MappingFunc {

	return func(key string) string {
		m := MustGetMap(mapName)
		v, ok := m[strings.TrimSpace(strings.ToLower(key))]
		if !ok {
			log.Error( "missing key ", key," in map ", mapName)
			return ""
		}
		return v
	}
}

调用:

const (
	M_ERROR_CODES_EN    = "error_codes_en"
	M_ERROR_CODES_ID    = "error_codes_id"
)

var getErrorMessageEn = util.LookupFuncWithDefaultKey(M_ERROR_CODES_EN, strconv.Itoa(defaultErrorId))
共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics