本文整理汇总了Golang中encoding/json.NewEncoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewEncoder函数的具体用法?Golang NewEncoder怎么用?Golang NewEncoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewEncoder函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: queryServerIDRetriever
func queryServerIDRetriever(w http.ResponseWriter, ids []string) {
s := make(chan map[string]string, len(ids))
db.ServerDB.GetHostsAndGameFromIDAPIQuery(s, ids)
hostsgames := <-s
if len(hostsgames) == 0 {
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(models.GetDefaultServerList()); err != nil {
writeJSONEncodeError(w, err)
}
return
}
serverlist, err := steam.Query(hostsgames)
if err != nil {
setNotFoundAndLog(w, err)
if err := json.NewEncoder(w).Encode(models.GetDefaultServerList()); err != nil {
writeJSONEncodeError(w, err)
return
}
return
}
if err := json.NewEncoder(w).Encode(serverlist); err != nil {
writeJSONEncodeError(w, err)
logger.LogWebError(err)
}
}
开发者ID:syncore,项目名称:a2sapi,代码行数:25,代码来源:retrievers.go
示例2: UpdateIndexSettings
func (s *ESAPIV0) UpdateIndexSettings(name string, settings map[string]interface{}) error {
log.Debug("update index: ", name, settings)
cleanSettings(settings)
url := fmt.Sprintf("%s/%s/_settings", s.Host, name)
if _, ok := settings["settings"].(map[string]interface{})["index"]; ok {
if set, ok := settings["settings"].(map[string]interface{})["index"].(map[string]interface{})["analysis"]; ok {
log.Debug("update static index settings: ", name)
staticIndexSettings := getEmptyIndexSettings()
staticIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["analysis"] = set
Post(fmt.Sprintf("%s/%s/_close", s.Host, name), s.Auth, "", s.HttpProxy)
body := bytes.Buffer{}
enc := json.NewEncoder(&body)
enc.Encode(staticIndexSettings)
bodyStr, err := Request("PUT", url, s.Auth, &body, s.HttpProxy)
if err != nil {
log.Error(bodyStr, err)
panic(err)
return err
}
delete(settings["settings"].(map[string]interface{})["index"].(map[string]interface{}), "analysis")
Post(fmt.Sprintf("%s/%s/_open", s.Host, name), s.Auth, "", s.HttpProxy)
}
}
log.Debug("update dynamic index settings: ", name)
body := bytes.Buffer{}
enc := json.NewEncoder(&body)
enc.Encode(settings)
_, err := Request("PUT", url, s.Auth, &body, s.HttpProxy)
return err
}
开发者ID:medcl,项目名称:elasticsearch-migration,代码行数:35,代码来源:v0.go
示例3: TodoShow
func TodoShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var todoId int
var err error
if todoId, err = strconv.Atoi(vars["todoId"]); err != nil {
panic(err)
}
todo := RepoFindTodo(todoId)
if todo.Id > 0 {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(todo); err != nil {
panic(err)
}
return
}
// If we didn't find it, 404
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
开发者ID:banlong,项目名称:cut2it-mediaResful,代码行数:26,代码来源:handlers.go
示例4: infoAPI
// Info endpoint api mocking
// curl http://127.0.0.1:8888/api/v0/malware/info/1234567890abcdef
func infoAPI(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hash := vars["hash"]
if hash == "1234567890abcdef" {
a := ArtRes{
Ssdeep: "1234567890",
Md5: "1234567890",
Sha1: "1234567890",
Sha256: "1234567890",
Sha512: "1234567890",
Format: "pe",
Symbols: []string{"a", "b"},
Imports: []string{"a", "b"},
Sections: []string{"a", "b"},
Arch: "amd64",
Strain: "",
Mutations: []string{"0987654321", "5647382910", "4536789013"},
Siblings: []string{""},
}
v := DataRes{
302,
"Asset already analysed",
a,
}
json.NewEncoder(w).Encode(v)
return
} else {
v := SearchRes{404, "This element does not exist", ""}
json.NewEncoder(w).Encode(v)
return
}
}
开发者ID:SecurityArtWork,项目名称:MEMT,代码行数:37,代码来源:memtDevServer.go
示例5: listContainersHandler
func listContainersHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
address := r.URL.Query().Get(":address")
if address != "" {
node, err := mainDockerProvisioner.Cluster().GetNode(address)
if err != nil {
return err
}
hasAccess := permission.Check(t, permission.PermNodeRead,
permission.Context(permission.CtxPool, node.Metadata["pool"]))
if !hasAccess {
return permission.ErrUnauthorized
}
containerList, err := mainDockerProvisioner.listContainersByHost(address)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(containerList)
}
appName := r.URL.Query().Get(":appname")
a, err := app.GetByName(appName)
if err != nil {
return err
}
hasAccess := permission.Check(t, permission.PermNodeRead,
permission.Context(permission.CtxPool, a.Pool))
if !hasAccess {
return permission.ErrUnauthorized
}
containerList, err := mainDockerProvisioner.listContainersByApp(appName)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(containerList)
}
开发者ID:reoring,项目名称:tsuru,代码行数:34,代码来源:handlers.go
示例6: DeleteAbility
func DeleteAbility(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
urlParams := mux.Vars(r)
strID := urlParams["id"]
ability := models.Ability{}
id, err := strconv.Atoi(strID)
if err != nil {
// handle error
message := models.APIMessage{"Id format invalid"}
json.NewEncoder(w).Encode(message)
} else {
database.DB.First(&ability, id)
if ability.ID == 0 {
message := models.APIMessage{"Ability not found"}
json.NewEncoder(w).Encode(message)
} else {
database.DB.Delete(&ability)
message := models.APIMessage{"Ability successful deleted"}
json.NewEncoder(w).Encode(message)
}
}
}
开发者ID:efrenfuentes,项目名称:go-authentication,代码行数:25,代码来源:abilities.go
示例7: TodoCreate
/*
Test with this curl command:
curl -H "Content-Type: application/json" -d '{"name":"New Todo"}' http://localhost:8080/todos
*/
func TodoCreate(w http.ResponseWriter, r *http.Request) {
Cors(w)
var todo Todo
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &todo); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
t := RepoCreateTodo(todo)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(t); err != nil {
panic(err)
}
}
开发者ID:azelenkovas,项目名称:test-service,代码行数:31,代码来源:handlers.go
示例8: Login
func (c *ApiConnection) Login(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
password := r.FormValue("password")
connection := c.dbConnection.LoginWithCredentials(email, password)
userID := fmt.Sprintf("%x", string(connection.Id))
log.Println(userID)
if connection != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
userMap := make(map[string]string)
userMap["token"] = userID
if err := json.NewEncoder(w).Encode(userMap); err != nil {
panic(err)
}
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
开发者ID:zarkopopovski,项目名称:godo,代码行数:29,代码来源:handlers.go
示例9: TaskCreate
/*
Test with this curl command:
*/
func TaskCreate(w http.ResponseWriter, r *http.Request) {
var v Node
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &v); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusBadRequest) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
uuid := uuid()
tasks[uuid.ID] = &v
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusAccepted)
if err := json.NewEncoder(w).Encode(uuid); err != nil {
panic(err)
}
return
}
开发者ID:owulveryck,项目名称:gorchestrator,代码行数:32,代码来源:executor_test.go
示例10: getCLHandler
func getCLHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
detail, err := getCLDetail(r.FormValue("cl"))
if err != nil {
skutil.ReportError(w, r, err, "")
return
}
if detail.Issue == 0 {
// Return successful empty response, since the user could still be typing.
if err := json.NewEncoder(w).Encode(map[string]interface{}{}); err != nil {
skutil.ReportError(w, r, err, "Failed to encode JSON")
}
return
}
patch, err := getCLPatch(detail, 0)
if err != nil {
skutil.ReportError(w, r, err, "")
return
}
clData, err := gatherCLData(detail, patch)
if err != nil {
skutil.ReportError(w, r, err, "")
return
}
if err = json.NewEncoder(w).Encode(clData); err != nil {
skutil.ReportError(w, r, err, "")
return
}
}
开发者ID:saltmueller,项目名称:skia-buildbot,代码行数:29,代码来源:chromium_perf.go
示例11: taskList
func (s *DockerServer) taskList(w http.ResponseWriter, r *http.Request) {
s.swarmMut.Lock()
defer s.swarmMut.Unlock()
if s.swarm == nil {
w.WriteHeader(http.StatusNotAcceptable)
return
}
filtersRaw := r.FormValue("filters")
var filters map[string][]string
json.Unmarshal([]byte(filtersRaw), &filters)
if filters == nil {
json.NewEncoder(w).Encode(s.tasks)
return
}
var ret []*swarm.Task
for i, task := range s.tasks {
var srvName string
for _, srv := range s.services {
if task.ServiceID == srv.ID {
srvName = srv.Spec.Name
break
}
}
if inFilter(filters["id"], task.ID) ||
inFilter(filters["service"], task.ServiceID) ||
inFilter(filters["service"], srvName) ||
inFilter(filters["node"], task.NodeID) ||
inFilter(filters["desired-state"], string(task.DesiredState)) {
ret = append(ret, s.tasks[i])
}
}
json.NewEncoder(w).Encode(ret)
}
开发者ID:docker,项目名称:dockercraft,代码行数:33,代码来源:swarm.go
示例12: GET_Nodes
func (a *App) GET_Nodes(w http.ResponseWriter, r *http.Request) {
sessionCopy := db.GetDatastore().Copy()
defer sessionCopy.Close()
params := r.URL.Query()
admin_state_str := params.Get("state")
collection := sessionCopy.DB(conf.SystemConfig.DBConfig.Database).C(models.COLL_NAME_STORAGE_NODES)
var nodes models.Nodes
if admin_state_str == "" {
if err := collection.Find(nil).All(&nodes); err != nil {
util.HttpResponse(w, http.StatusInternalServerError, err.Error())
logger.Get().Error("Error getting the nodes list. error: %v", err)
return
}
} else {
nodes, err = getNodesWithState(w, admin_state_str)
if err != nil {
util.HttpResponse(w, http.StatusInternalServerError, err.Error())
logger.Get().Error("Error getting the nodes list. error: %v", err)
return
}
}
if len(nodes) == 0 {
json.NewEncoder(w).Encode([]models.Node{})
} else {
json.NewEncoder(w).Encode(nodes)
}
}
开发者ID:GowthamShanmugam,项目名称:skyring,代码行数:29,代码来源:nodes.go
示例13: SubmissionCreate
// SubmissionCreate accepts POST request
func SubmissionCreate(w http.ResponseWriter, r *http.Request) {
var submission Submission
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &submission); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(submission); err != nil {
panic(err)
}
}
开发者ID:xcv58,项目名称:go-restful-api,代码行数:28,代码来源:handlers.go
示例14: GetPhoto
func GetPhoto(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var photoId string
var ok bool
if photoId, ok = vars["photoId"]; !ok {
panic("cannot find {photoId}")
}
photo, err := persistence.RepoFindPhoto(photoId)
if err == nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(photo); err != nil {
panic(err)
}
return
}
// If we didn't find it, 404
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(responseErrors.JSONErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
开发者ID:wrightm,项目名称:selfie-roulette,代码行数:25,代码来源:getPhoto.go
示例15: TodoCreate
func TodoCreate(w http.ResponseWriter, r *http.Request) {
db := InitDB()
var todo Todo
response := TodoResponse{Error: true}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
spew.Dump(body)
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.Unmarshal(body, &todo); err != nil {
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
} else {
db.Create(&todo)
response.Error = false
response.Data = &todo
}
json.NewEncoder(w).Encode(response)
}
开发者ID:foysalit,项目名称:godo,代码行数:30,代码来源:handlers.go
示例16: MunicipalIndex
//handlers for municipality
func MunicipalIndex(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var lat float64
var lon float64
var err error
if lat, err = strconv.ParseFloat(vars["lat"], 64); err != nil {
panic(err)
}
if lon, err = strconv.ParseFloat(vars["lon"], 64); err != nil {
panic(err)
}
m := RepoFindCourtByAddress(lat, lon)
if m.Id >= 0 {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(m); err != nil {
panic(err)
}
return
}
// If we didn't find it, 404
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
开发者ID:Dacode45,项目名称:gh5server,代码行数:31,代码来源:handlers.go
示例17: onGetChatHistory
func (c *ChatService) onGetChatHistory(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
log.Println("Get chat history...")
groupId := p.ByName("id")
queryParams := req.URL.Query()
var offset uint = 0
var limit uint = 20
if o, err := strconv.ParseUint(queryParams.Get("offset"), 10, 32); err == nil {
offset = uint(o)
}
if l, err := strconv.ParseUint(queryParams.Get("limit"), 10, 32); err == nil {
limit = uint(l)
}
log.Println("Limit =", limit, "Offset =", offset)
log, err := c.chatStore.GetMessagesFor(groupId, offset, limit)
if err == nil {
response := make(map[string]interface{})
response["limit"] = limit
response["offset"] = offset
response["messages"] = log
response["id"] = groupId
json.NewEncoder(w).Encode(response)
} else {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorMessage{
Error: err.Error(),
})
}
}
开发者ID:CHH-Darick,项目名称:raspchat,代码行数:32,代码来源:chat_service.go
示例18: TicketIndex
//handlers for Ticket
func TicketIndex(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
driver_licenses, ok := params["driver_license"]
if ok {
driver_license := string(driver_licenses[0])
tic := RepoFindTicketByDriverLicenseNumber(driver_license)
if tic.Id > 0 {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(tic); err != nil {
panic(err)
}
} else {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
} else {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(gTickets); err != nil {
panic(err)
}
}
}
开发者ID:Dacode45,项目名称:gh5server,代码行数:28,代码来源:handlers.go
示例19: CreateAbility
func CreateAbility(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var newAbility models.NewAbility
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048676))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &newAbility); err != nil {
message := models.APIMessage{"Input format invalid"}
json.NewEncoder(w).Encode(message)
} else {
var ability models.Ability
ability.Name = newAbility.Name
database.DB.Create(&ability)
if database.DB.NewRecord(ability) {
message := models.APIMessage{"Error creating ability"}
json.NewEncoder(w).Encode(message)
} else {
json.NewEncoder(w).Encode(ability)
}
}
}
开发者ID:efrenfuentes,项目名称:go-authentication,代码行数:33,代码来源:abilities.go
示例20: CourtCreate
func CourtCreate(w http.ResponseWriter, r *http.Request) {
var court Court
var err error
//Check if malicious user is trying to overload the server
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &court); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
if court, err = RepoCreateCourt(court); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(court); err != nil {
panic(err)
}
}
开发者ID:Dacode45,项目名称:gh5server,代码行数:34,代码来源:handlers.go
注:本文中的encoding/json.NewEncoder函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论