本文整理匯總了Golang中encoding/json.NewEncoder函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewEncoder函數的具體用法?Golang NewEncoder怎麽用?Golang NewEncoder使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewEncoder函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
}
}
示例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
}
示例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)
}
}
示例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
}
}
示例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)
}
示例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)
}
}
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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
}
}
示例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)
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
示例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)
}